1

I am trying to run a unit test using Jest in React, on my componentDidMount() method, and only that method. my componentDidMount() is as follows:

componentDidMount() {
    //Delay to simulate welcome loading screen
    const delay = 2000;
    setTimeout(() => {
      this.setState({ appLoaded: true }); //this line has no coverage, according to IDE
    }, delay);
  }

I tried to follow this and I got a bunch of errors. One of the big differences is that the sample given has a componentDidMount() method that is nothing like mine. My componentDidMount() has a local function in it, theirs doesn't. How can I unit test this?

also, in particular, I want to test the line that says this.setState({ appLoaded: true }); as it's the line that's said to not be covered.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
user11039951
  • 141
  • 9

1 Answers1

1

As you use setTimeout, it make sense to use fake timers: runTimersToTime or advanceTimersByTime (if you're using jest v ^22.0.0). I.e.:

import { shallow } from 'enzyme';

jest.useFakeTimers();

it('tracks app loaded', () => {
  const wrapper = shallow(<YourAwesomeComponent />);
  expect(wrapper.state('appLoaded')).toBeFalsy();
  jest.runTimersToTime(2000);
  expect(wrapper.state('appLoaded')).toBeTruthy();
});
Alejandro
  • 5,834
  • 1
  • 19
  • 36