Ad

Jest/Enzyme | Test A Function Call In ComponentDidMount

What to do when you want to test that a function is been called, on componentDidMount() React lifecycle Method. Basically the component code looks like this:

  state = {
    randomStateToPopulate: []
  };

  // Test componentDidMount
  componentDidMount() {
    this.randomFunction();
  }

  randomFunction= () => {
    listRandomData().then(({ data }) => {
      this.setState({ randomStateToPopulate: data });
    });
  };

So, how to you actually test this case?

Ad

Answer

This is the case scenario you want to test. If the componentDidMount is being called, check that it has been called only once, or as many times you want.

Your test. I have the explanation in comments below

    // Inside your general `Describe`
  let wrapper;
  const props = {
    // Your props goes here..
  };
  beforeEach(() => {
    wrapper = shallow(<YourComponent {...props} />);
  });

    it('should check `componentDidMount()`', () => {
      const instance = wrapper.instance(); // you assign your instance of the wrapper
      jest.spyOn(instance, 'randomFunction'); // You spy on the randomFunction
      instance.componentDidMount();
      expect(instance.randomFunction).toHaveBeenCalledTimes(1); // You check if the condition you want to match is correct.
    });

You can abstract, this case to do more complex things, but the basic gist of it is the above one. If you have a more detailed or better solution, please post it. Thanks!!

Ad
source: stackoverflow.com
Ad