【问题标题】:React - jest Use custom state to check conditions in componentReact - jest 使用自定义状态检查组件中的条件
【发布时间】:2020-12-02 04:08:15
【问题描述】:

我想使用不同的状态值来检查 else 是否参与函数 - 反应单元测试 所以我可以得到全覆盖[点击这里查看代码-左-测试代码-右-功能检查]

【问题讨论】:

    标签: reactjs redux jestjs enzyme


    【解决方案1】:

    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 语句中的代码有关。我认为这应该为您提供全面的覆盖。

    【讨论】:

    • 正如我之前所说,我已经设置了状态但它没有反映,它总是考虑组件构造函数中提到的状态
    【解决方案2】:
    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);
    })
    

    【讨论】:

      猜你喜欢
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 2022-10-08
      • 1970-01-01
      相关资源
      最近更新 更多