开玩笑:检查一个模拟模块函数被调用了多少次

时间:2018-10-19 03:36:24

标签: jestjs

我在代码中使用模块waait来执行以下操作:

import * as wait from 'waait';
await wait(500);

我创建了一个手动模拟:

module.exports = (() => {
  return Promise.resolve();
});

然后我想在测试中拥有这样的断言:

import * as wait from 'waait';
expect(wait).toHaveBeenCalledTimes(1);
expect(wait).toHaveBeenLastCalledWith(1000);

当我运行它时,我得到:

expect(jest.fn())[.not].toHaveBeenCalledTimes()

jest.fn() value must be a mock function or spy.
Received: undefined

1 个答案:

答案 0 :(得分:1)

您创建的手动模拟完全不是mock,而是fake(即替代实现)。

您甚至不需要它。您可以删除手动模拟并像这样编写测试:

import * as wait from 'waait';

jest.mock('waait');
wait.mockResolvedValue(undefined);

it('does something', () => {
    // run the tested code here
    // ...

    // check the results against the expectations
    expect(wait).toHaveBeenCalledTimes(1);
    expect(wait).toHaveBeenLastCalledWith(1000);
});