在 Node 模块导出的函数上使用 `jest.spyOn`

Gar*_*ary 5 unit-testing mocking spy node.js jestjs

Jest中,为了监视(以及可选地模拟实现)方法,我们执行以下操作:

const childProcess = require('child_process');
const spySpawnSync = jest.spyOn(childProcess, 'spawnSync').mockImplementation();
Run Code Online (Sandbox Code Playgroud)

这允许我们spySpawnSync检查上次调用它时使用的参数,如下所示:

expect(spySpawnSync).lastCalledWith('ls');
Run Code Online (Sandbox Code Playgroud)

但是,对于导出函数的 Node 模块(例如execa包)来说,这是不可能的。

我尝试了以下各项,但没有一个监视或模拟该功能:

// Error: `Cannot spy the undefined property because it is not a function; undefined given instead`
jest.spyOn(execa);

// Error: `Cannot spyOn on a primitive value; string given`
jest.spyOn('execa');

// Error: If using `global.execa = require('execa')`, then does nothing. Otherwise, `Cannot spy the execa property because it is not a function; undefined given instead`.
jest.spyOn(global, 'execa');
Run Code Online (Sandbox Code Playgroud)

因此,是否有任何方法可以监视导出函数的模块,例如execa在给定的示例中?

Oli*_*nce 0

我有完全相同的需求和问题execa,这就是我如何让它发挥作用:

import execa from 'execa'


jest.mock('execa', () => jest.fn())

test('it calls execa', () => {
  runSomething()
  expect(execa).toHaveBeenCalled()
})

Run Code Online (Sandbox Code Playgroud)

所以基本上,由于导入的模块是函数本身,因此您要做的就是使用 模拟整个模块jest.mock,然后简单地返回一个 Jest 模拟函数作为其替换。

由于jest.fn()jest.spyOn()在幕后依赖的,因此您可以在测试中受益于相同的断言方法:)