title: Mocking a function called inside a then block in a React Component
body: <p>I am trying to test if a function(passed as props to the React component) is getting called with the expected arguments by creating a mock of it using Jest.</p>
  
  <p>Below is the function that I am trying to test:</p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>handlerFunction() {
  
  let response = [];
  this.props.files.forEach((file) =&gt; {
  
    let responseObject= this.getResponse(file);
    responseObject.then((result) =&gt; {
  
      response.push({
  
        fileName: file.name,
        records: result,
  
      });
  
      this.props.sendResponseData(response);
  
    });
  
  });
  
  }
  
  getResponse(file) {
  
  return new Promise((resolve, reject) =&gt; {
  
    axios.post(URL, file).then((response) =&gt; {
  
      resolve(response.data);
  
    }).catch((error) =&gt; {
  
      reject(console.error(error));
  
    });
  
  });
  
  }
  </code></pre>
  
  <p>handlerFunction() calls getResponse() which makes an AJAX call and returns the response data in a Promise. handlerFunction() takes the response data returned from getResponse() and pushes the response data and corresponding file's name into response[] and then calls this.props.sendResponseData() with it. I mocked getResponse() and made it return a dummy response data and testing if this.props.sendResponseData() is getting called with the dummyResponse that I created in test class. </p>
  
  <p>Here is the code that I have written to test the above function in a React Component:</p>
  
  <pre class="lang-js prettyprint-override"><code>it('handlerFunction', () =&gt; {
  files= [dummyFile];
  sendResponseData = jest.fn();
  
  let wrapper = shallow(&lt;RenderComponent
                         files={files}
                         sendResponseData={sendResponseData}
                         /&gt;);
  
  let dummyAJAXResponse = {};
  let dummyResponse = [{ fileName: 'file', records: dummyAJAXResponse }];
  
  const getResponseMock= jest.fn(() =&gt; {
  
   return new Promise((resolve) =&gt; {
  
     resolve(dummyAJAXResponse);
  
   });
  
  });
  wrapper.instance().getResponse= getResponseMock ;
  wrapper.update();
  wrapper.instance().handlerFunction();
  expect(sendResponseData).toBeCalledWith(dummyResponse);
  })
  </code></pre>
  
  <p>When I try to run this test, it fails and says as following:</p>
  
  <pre class="lang-js prettyprint-override"><code>expect(jest.fn()).toBeCalledWith(expected)
  
  Expected mock function to have been called with:
    [[{"fileName": "file", "records": {}}]]
  But it was not called.
  </code></pre>
  
  <p>Any help would be greatly appreciated. Thanks!</p>