简体   繁体   中英

How to test a React component that update over time with Jest and Enzyme?

I have this React Component

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>
}}

And I want to express a test like this

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

currently the first expect pass but the second fails

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

How can I properly test this component ?

Use Full Rendering API, mount(...)

Full DOM rendering is ideal for use cases where you have components that may interact with DOM APIs, or may require the full lifecycle in order to fully test the component (ie, componentDidMount etc.)

You can use mount() instead of shallow() like

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();
    });
});

Or you can pass additional object to shallow to instrument it to run lifecycle methods

options.disableLifecycleMethods: (Boolean [optional]): If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after setProps and setContext.

const options = {
  lifecycleExperimental: true,
  disableLifecycleMethods: false 
};

const wrapper = shallow(<Timer i={10} />, options);

I tested it. It works.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM