I am trying to test whether componentWillMount was called and for that my test is
test('calls `componentWillMount` before rendering', () => {
let fn = jest.fn(SomeComponent.prototype.componentWillMount)
mount(<SomeComponent />)
expect(fn).toHaveBeenCalled()
})
But even though the componentWillMount method is called, the test does not pass. What am I missing here?
I don't believe the above answer addresses the issue. Which is jest allow you to spyOn a method but does not allow you to
callThrough
while spying on its call status. The solution that worked best for me is to setup the test with a component that hascomponentWillMount
defined. Leaning on jest will just make things more complicated.Try this:
I would first
spy
on the component'scomponentWillMount
method but also use.and.CallThrough()
to prevent it from mocking its contents. Hope this helps:I don't know if the other answers have helped with your question, but you shouldn't need to test componentWillMount. React should already do that testing for you.
More relevant to your testing would be to test the functions or actions you are putting in that method for your component.
If you are making some API call, running a function based on props, or anything else, that is what you should be testing for. Mock the function/action/code that
componentWillMount
triggers, and make assertions and expectations on that.Example:
Component:
Tests: