React-开玩笑使用自定义状态检查组件中的条件

问题描述

我想使用不同的状态值来检查函数中是否还有其他部分-反应单元测试 这样我就可以获得完整的报道[单击此处查看代码左-测试代码右-功能进行检查]

enter image description here

解决方法

据我所知,您可以通过使用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);
})