React 单元测试:使用 React Testing Library 模拟 state 变化
使用 React Testing Library 模拟 state 变化,需要调用 fireEvent 方法模拟用户事件,例如点击按钮、输入文本等操作,然后在断言中验证 state 的变化是否符合预期。
下面是一个示例:
import React, { useState } from 'react';
import { render, fireEvent } from '@testing-library/react';
function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return (
<div>
<button onClick={increment}>+</button>
<p>Count: {count}</p>
</div>
);
}
it('increments count when button is clicked', () => {
const { getByText } = render(<Counter />);
const button = getByText('+');
const count = getByText('Count: 0');
fireEvent.click(button);
expect(count).toHaveTextContent('Count: 1');
fireEvent.click(button);
expect(count).toHaveTextContent('Count: 2');
});
在这个示例中,我们通过 render 函数渲染了 Counter 组件,并使用 getByText 方法获取了 '+' 按钮和初始值为 0 的计数器。接着,我们模拟了两次点击按钮的事件,并在断言中验证了计数器的值是否符合预期。
原文地址: https://www.cveoy.top/t/topic/ohbc 著作权归作者所有。请勿转载和采集!