Jest mock function calls is not counted

Viewed 4498

I want to mock a function post from an object. I did it like this:

jest.mock('../../apis.js', () => {
  return () => {
    return {
      post: jest.fn(() => {
        console.log('POST was called !');
        return Promise.resolve();
      }),
    };
  };
});

Then, I make my require:

const apis = require('../../apis');

Finally I call my service which will call the post() function from apis module:

client.doPost()
  .then(() => {
    console.log('count: ', apis().post.mock.calls.length);
    expect((apis().post)).toBeCalled();
  });

The doPost() function calls the mocked post() one ('POST was called !' message is printed) but count is equal to 0 and expect fails.

2 Answers

This needs to be checked but I guess that the variable you access in your apis().post.mock.calls.length call is not the same as the one that is used in your client.doPost() call.

Indeed, when you call apis(), your mock returns a new object at each call.

What you want to do is storing the stub in a dedicated variable and access it in your then() test:

const postStub = jest.fn(() => {
  console.log('POST was called !');
  return Promise.resolve();
});

jest.mock('../../apis.js', () => {
  return () => {
    return {
      post: postStub,
    };
  };
});

Then to use it (should be on the same file of course):

client.doPost()
  .then(() => {
    console.log('count: ', postStub.mock.calls.length);
    expect((apis().post)).toBeCalled();
  });

Workaround

global.iPost=0;

jest.mock('../../apis.js', () => {
  return () => {
    return {
      post: jest.fn(() => {
        console.log('POST was called !');
        global.iPost++;
        return Promise.resolve();
      }),
    };
  };
});

expect(global.iPost).toEqual(1)
Related