【发布时间】:2020-12-02 04:08:15
【问题描述】:
【问题讨论】:
标签: reactjs redux jestjs enzyme
【问题讨论】:
标签: reactjs redux jestjs enzyme
Ciao,据我所知,您可以通过使用 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);
})
【讨论】: