[英]React -Jest Invoke UseEffect
我在更改状态的代码中有依赖性 useeffect -
useEffect(()=>{
if(open)
{
setOpen(false);
}
},[open]); //open is a state variable which changes with setOpen(true/false);
我的代码覆盖率为此显示红线。 我怎样才能用玩笑来测试这个? (由于某些项目原因,我不能使用酶,决定权不在我手中)
我试过了 -
beforeAll(()=>{
useState.mockImplementation(callback=>{
return callback({
open:true
})
})
});
test("Check State",async ()=>{
render(<ControlToRender/>);
await act(()=> expect(open).toBe(false);
})
当我这样做时出现错误 - npm 运行测试 -
useState.mockImplementation is not a function
我相信您应该将组件作为 balckbox 进行测试,而不是 useState 内部实现本身。 类似于 - 用户操作 - 预期行为(元素是否可见)。 mocking global useState 的做法是不可持续的。 如果另一个开发人员在组件中添加另一个 useState 怎么办?
更多行为驱动示例:
test("Given XXX the alert should be visible",async ()=>{
render(<ControlToRender/>);
await act(()=> {
const errorMessageNode = screen.getByRole("alert");
expect(errorMessageNode).toBeVisible();
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.