Unk*_*per 5 javascript reactjs jestjs react-testing-library react-hooks
成分:
const MyComponent = props => {
const {price} = props;
const result1 = useResult(price);
return (
<div>...</div>
)
}
Run Code Online (Sandbox Code Playgroud)
定制挂钩:
export const useResult = (price) => {
const [result, setResult] = useState([]);
useEffect(() => {
const data = [{price: price}]
setResult(data);
}, [price]);
return result;
};
Run Code Online (Sandbox Code Playgroud)
开玩笑测试:
it('should ...', async () => {
render(
<MyComponent price={300}/>)
)
await waitFor(() => {
expect(...).toBeInTheDocument();
});
});
Run Code Online (Sandbox Code Playgroud)
上面的代码确实发生的是MyComponent,当运行测试时,仅渲染一次而不是两次(当应用程序运行时)。初始渲染后,其中result1是一个空数组,useEffect正在useResult运行,并且由于 导致状态发生变化setResult(data),我应该期望MyComponent重新渲染。然而,情况并非如此,result1仍然等于 ,[]而它应该等于[{price:300}]。
因此,测试中的自定义挂钩的行为似乎与真实应用程序不同。我认为通过调用它们的组件间接测试它们是可以的。
对上述内容有什么解释/想法吗?
更新
引发上述错误行为的问题是状态突变!它适用于应用程序,但不适用于测试!我的错误是尝试使用push将一个元素添加到作为状态变量的数组中......
小智 -1
你可以做:
The test will have to be async: it('should ...', async() => { ....
await screen.findByText('whatever');
This is async so it will wait to find whatever and fail if it can't find it
or you can do
await waitFor (() => {
const whatever = screen.getByText('whatever');
expect(whatever).toBeInTheDocument();
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7270 次 |
| 最近记录: |