不计算 Jest 模拟函数调用

Nas*_*oud 2 unit-testing mocking jestjs

我想从一个对象模拟一个函数帖子。我是这样做的:

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

然后,我提出我的要求:

const apis = require('../../apis');
Run Code Online (Sandbox Code Playgroud)

最后我调用我的服务,它将调用模块中的post()函数apis

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

doPost()函数调用了模拟的post()('POST was called !' 消息被打印)但是count is equal to 0并期望失败。

Val*_*inH 5

这需要检查,但我猜您在apis().post.mock.calls.length调用中访问的变量与调用中使用的变量不同client.doPost()

实际上,当您调用 时apis(),您的模拟在每次调用时都会返回一个新对象。

您想要做的是将存根存储在专用变量中并在您的then()测试中访问它:

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

jest.mock('../../apis.js', () => {
  return () => {
    return {
      post: postStub,
    };
  };
});
Run Code Online (Sandbox Code Playgroud)

然后使用它(当然应该在同一个文件上):

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