Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test React component method is calling function pass as a prop

I want to test that when calling a method from a React component it trigger a function pass to the component as a props. The method is something like this:

customMethod() {
  // Do something

  this.props.trackEvent({
    category: 'eventCategory',
    action: 'eventAction',
    label: 'eventAction',
  });

  // Do something else
}

The method can be called from different ways, so I want just to make a generic test: if customMethod is called, should trigger this.props.trackEvent with data.

Is there a way to trigger a method call using jest and/or enzyme? I've read about doing something like this:

const wrapper = shallow(<AdPage {...baseProps} />);
wrapper.instance().customMethod();

But it is not working… any ideas. I'm pretty new in the testing, so maybe should I use a different approach to this kind of tests?

like image 464
Coluccini Avatar asked Aug 24 '17 16:08

Coluccini


1 Answers

Assuming your customMethod is a component method, I would test it like this:

(1) Fake your trackEvent prop as a jest.fn() when you create the wrapper.

(2) Call your customMethod using wrapper.instance().customMethod();

(3) Ensure props.trackEvent to haveBeenCalledWith the argument you mentioned.

As an example:

test('customMethod should call trackEvent with the correct argument', () => {
  const baseProps = {
    // whatever fake props you want passed to the component
    // ...
    trackEvent: jest.fn(),
  };
  const wrapper = shallow(<AdPage {...baseProps} />);

  wrapper.instance().customMethod();

  expect(baseProps.trackEvent).toHaveBeenCalledTimes(1);

  expect(baseProps.trackEvent).toHaveBeenCalledWith({
    category: 'eventCategory',
    action: 'eventAction',
    label: 'eventAction',
  });
}); 
like image 75
nbkhope Avatar answered Oct 16 '22 12:10

nbkhope