Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - test method that passes to child component

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.

like image 229
Nazar Avatar asked Oct 16 '22 13:10

Nazar


1 Answers

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
like image 113
Kai Hao Avatar answered Oct 27 '22 09:10

Kai Hao