这个问题是关于:如何测试使用useEffect
钩子和useState
钩子的组件,使用react-testing-library
.
我有以下组件:
function MyComponent() {
const [state, setState] = useState(0);
useEffect(() => {
// 'request' is an async call which takes ~2seconds to complete
request().then(() => {
setState(1);
});
}, [state]);
return <div>{state}</div>
}
当我渲染这个应用程序时,我看到的行为如下:
- 该应用程序最初呈现
0
- 大约 2 秒后,应用程序呈现
1
现在,我想使用 and 来测试和断言这种react-testing-library
行为jest
。
这是我到目前为止所拥有的:
import {render, act} from '@testing-library/react';
// Ignoring the describe wrapper for the simplicity
test('MyComponent', async () => {
let result;
await act(async () => {
result = render(<MyComponent />);
});
expect(result.container.firstChild.textContent).toBe(1);
})
测试通过。但是,我还想断言用户最初看到应用程序呈现的事实0
(在1
2 秒后呈现之前)。
我怎么做?提前致谢。