Reputation: 141
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.
Upvotes: 1
Views: 99
Reputation: 5944
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();
});
Upvotes: 1