【问题标题】:How to test a React component that update over time with Jest and Enzyme?如何使用 Jest 和 Enzyme 测试随时间更新的 React 组件?
【发布时间】:2017-04-23 19:17:24
【问题描述】:

我有这个 React 组件

export class Timer extends Component {

constructor(props) {
    super(props);
    this.state = {i : props.i};
}

componentDidMount(){
    this.decrementCounter();
}

decrementCounter(){
    if(this.state.i < 1){
        return;
    }
    setTimeout(() => {
        this.setState({i : this.state.i - 1})
        this.decrementCounter()}, 1000);
}

render(){
    return <span>{this.state.i}</span>
}}

我想表达一个这样的测试

jest.useFakeTimers();
it('should decrement timer ', () => {
    const wrapper = shallow(<Timer i={10} />);
    expect(wrapper.text()).toBe("10");
    jest.runOnlyPendingTimers();
    expect(wrapper.text()).toBe("9");
});

目前第一个期望通过但第二个失败

Expected value to be (using ===):
      "9"
    Received:
      "10"

如何正确测试这个组件?

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

    使用Full Rendering API, mount(...)

    完整的 DOM 渲染非常适合有组件的用例 可能与 DOM API 交互,或者可能需要完整的生命周期 为了全面测试组件(即componentDidMount等)

    您可以使用mount() 代替shallow() 之类的

    import React from 'react';
    import { mount, /* shallow */ } from 'enzyme';
    import Timer from './index';
    
    describe('Timer', () => {
        it('should decrement timer ', () => {
            jest.useFakeTimers();
    
            const wrapper = mount(<Timer i={10} />);
            expect(wrapper.text()).toBe("10");
            jest.runOnlyPendingTimers();
            expect(wrapper.text()).toBe("9");
    
            jest.useRealTimers();
        });
    });
    

    或者您可以将其他对象传递给 shallow 以检测它以运行生命周期方法

    options.disableLifecycleMethods: (Boolean [optional]): 如果设置为 true, 组件上没有调用 componentDidMount,并且 在 setProps 和 setContext 之后不会调用 componentDidUpdate。

    const options = {
      lifecycleExperimental: true,
      disableLifecycleMethods: false 
    };
    
    const wrapper = shallow(<Timer i={10} />, options);
    

    我测试过了。它有效。

    hinok:~/workspace $ npm test
    
    > c9@0.0.0 test /home/ubuntu/workspace
    > jest
    
     PASS  ./index.spec.js (7.302s)
      Timer
        ✓ should decrement timer  (28ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        8.162s
    Ran all test suites.
    

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 2017-02-12
      • 2018-08-20
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多