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?
Try this:
test('calls `componentWillMount` before rendering', () => {
const onWillMount = jest.fn();
SomeComponent.prototype.componentWillMount = onWillMount;
mount(<SomeComponent />);
expect(onWillMount).toBeCalled();
});
I would first spy
on the component's componentWillMount
method but also use .and.CallThrough()
to prevent it from mocking its contents. Hope this helps:
it('should check that the componentWillMount method is getting called', () => {
spyOn(SomeComponent.prototype, 'componentWillMount').and.callThrough();
const wrapper = mount(<SomeComponent />);
expect(wrapper).toBeDefined();
expect(SomeComponent.prototype.componentWillMount).toHaveBeenCalledTimes(1);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With