如何解决React-开玩笑使用自定义状态检查组件中的条件
我想使用不同的状态值来检查函数中是否还有其他部分-反应单元测试 这样我就可以获得完整的报道[单击此处查看代码左-测试代码右-功能进行检查]
解决方法
据我所知,您可以通过使用setState设置状态(就像您已经在测试中所做的那样)然后重新调用componentInstance.handleLogin(event)
来获得完整的覆盖范围。像这样:
const event = { preventDefault: jest.fn };
wrapper.setState({username: "user",password: "pass"}); // this should cover if(username && password)
componentInstance.handleLogin(event);
expect(...)
wrapper.setState({username: "user",password: undefined}); // this should cover if(username && !password)
componentInstance.handleLogin(event);
expect(...)
wrapper.setState({username: undefined,password: "pass"}); // this should cover if(!username && password)
componentInstance.handleLogin(event);
expect(...)
wrapper.setState({username: undefined,password: undefined}); // this should cover if(!username && !password)
componentInstance.handleLogin(event);
expect(...)
在两次调用之间,您可以expect
与if语句中的代码有关。我认为这应该为您提供全面的报道。
it('handleLogin with different conditions',() => {
const handleLogin = jest.fn();
const event = { preventDefault: jest.fn() };
const wrapper = mount(
<MemoryRouter
initialEntries={[{ pathname: '/',key: 'testKey',state: {} }]}
>
<Provider store={store}>
<Login handleLogin={handleLogin} />
</Provider>
</MemoryRouter>
);
const componentInstance = wrapper.find('Login').instance();
componentInstance.setState({ username: "user",password: "pass" });
componentInstance.handleLogin(event);
componentInstance.setState({ username: "user",password: "" });
componentInstance.handleLogin(event);
componentInstance.setState({ username: "",password: "pass" });
componentInstance.handleLogin(event);
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。