0

Learning unit-testing, I am trying to use Jest to test React components. But i ran into an error while testing a method of a component that calls another method, that resides into another project entirely and then the parent method changes the state of it's component, so everything on the other method that is being called is normally undefined, therefore resulting on this test error. Can anyone guide me how to approach this problem? Supposing that the method being tested is:

methodToBeTested() {
    methodResidingIntoAnotherProject();
    this.setState({someState: true}); // someState is initially false
}

And the testing:

describe("testing the component's behaviour"), () => {
    it("testing the methodToBeTested", () => {
       const {wrapper} = setup();
       wrapper.setState({someState: false});
       wrapper.instance().methodToBeTested();

    expect(wrapper.state().someState).toEqual(true);
    });
});

The wrapper and the whole setup works, because i have tried some other structural tests, that have passed. The error that is being thrown is: "TypeError: Cannot read property 'someVariable' of undefined". The 'someVariable' is in the nested method.

minus.273
  • 755
  • 11
  • 24
  • 2
    refer to this question, which explains how to mock any thridparty module https://stackoverflow.com/questions/46158728/how-to-mock-third-party-modules-with-jest – abhirathore2006 Jan 23 '18 at 12:07
  • @abhirathore2006 Thank you. Is there any other approach though to simply ignore or suppose that the thirdparty module has been run successfully, since i am only interested on the what the component's method does, which is changing the state. – minus.273 Jan 23 '18 at 12:13
  • if your third-party method is pure means you can predict the output of given input then you don't need to mock it at all. just change your expected output as the result of the third-party method – abhirathore2006 Jan 23 '18 at 12:17
  • @abhirathore2006 well, the third-party method is not pure, that's the issue. Because even when i do as you suggest, it still gives the same error. – minus.273 Jan 23 '18 at 12:22
  • in that case, simply mock it, so it won't impact your tests – abhirathore2006 Jan 23 '18 at 12:24
  • @abhirathore2006 Understood. Many thanks! – minus.273 Jan 23 '18 at 12:26

0 Answers0