Jest:检查模拟模块函数被调用了多少次

jez*_*nag 4 jestjs

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

import * as wait from 'waait';
await wait(500);
Run Code Online (Sandbox Code Playgroud)

我创建了一个手动模拟:

module.exports = (() => {
  return Promise.resolve();
});
Run Code Online (Sandbox Code Playgroud)

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

import * as wait from 'waait';
expect(wait).toHaveBeenCalledTimes(1);
expect(wait).toHaveBeenLastCalledWith(1000);
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到:

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

jest.fn() value must be a mock function or spy.
Received: undefined
Run Code Online (Sandbox Code Playgroud)

axi*_*iac 9

您创建的手动模拟根本不是模拟而是假的(即替代实现)。

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

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);
});
Run Code Online (Sandbox Code Playgroud)