node.jsunit-testingmocha.jsintegration-testingfetch-mock

Mocking fetch POST


I am writing test case for below function:

handleShare(response, payload) {
    ShareUtils.listUsers()
      .then((users) => {
          users.forEach(user => userList.push({
              name: user.name,
              id: user.id)
          });
          return SessionUtils.getSessionData(SESSION_ID));
      })
  .then((sessionData) => {
    //construct share object
    return fetch('http://myEndpoint', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  })
  .then(r => r.json())
  .then((response) => {
    Logger.log(response)
  })
  .catch((err) => {
    ErrorHandler.error(err)
  });
}

And my test case is

describe('Share Controller', function() {
  it('should call handleShare correctly', function(done) {
    let listUsers = sinon.stub(ShareUtils, 'listUsers').resolves(listOfUsers);
    let sessionData = sinon.stub(SessionUtils, 'getSessionData').resolves(slackSessionData);
    fetchMock.mock({
        name: 'share',
        matcher: '/myEndpoint/',
        method: 'POST',
        response: 'ok'
      })
      .catch();
    ShareController.handleShare({}, payload);
    console.log(fetchMock.done());
    expect(fetchMock.called()).to.be.true;
    done();
  });
});

But whenever I run test case, it outputs AssertionError: expected false to be true

Am I missing something?I have setup mocha test suite correctly and every other test is running fine but this fetch mocking has been real trouble. Thanks for the help in advance.


Solution

  • I was missing content-type header while mocking!