I'm new in testing React component, so I'm trying test some method in parent component that passes to child component as props. I use Jest and Enzyme for this.
My test:
it('should be able to call myMethod callback', () => {
const mockFn = jest.fn();
ParentComponent.prototype.myMethod = mockFn;
const wrapper = Enzyme.shallow(<ParentComponent />);
wrapper.find('ChildComponent').props().myMethod();
expect(mockFn).toHaveBeenCalledTimes(1);
});
The test passed but myMethod didn't invoke (myMethod doesn't covered by tests).
When I use:
wrapper.instance().myMethod = mockFn;
instead of:
ParentComponent.prototype.myMethod = mockFn;
everything is the opposite - myMethod is invoked, but the test is failed with error:
expect(jest.fn()).toHaveBeenCalledTimes(1)
Expected mock function to have been called one time, but it was called zero times.
How can I solve this? Thanks in advance.
You are assigning myMethod
to a mock function which doesn't do anything, not even your original myMethod
. When you are creating jest.fn()
, what it basically does is creating a dummy mock function which doesn't do anything. So when you call wrapper.find('ChildComponent').props().myMethod()
, it just call that function but not your myMethod
.
What you might want to do is to spy on your method instead.
jest.spyOn(ParentComponent.prototype, 'myMethod'); // ParentComponent.prototype.myMethod is now a mock function
expect(ParentComponent.prototype.myMethod).toHaveBeenCalledTimes(1); // it works
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