In Jest https://jestjs.io,为了监视(并可选择模拟实现)方法,我们执行以下操作:
const childProcess = require('child_process');
const spySpawnSync = jest.spyOn(childProcess, 'spawnSync').mockImplementation();
这允许我们使用spySpawnSync
检查上次调用它时使用的参数,如下所示:
expect(spySpawnSync).lastCalledWith('ls');
但是,对于导出函数的 Node 模块来说这是不可能的,例如execa https://www.npmjs.com/package/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');
因此,有什么方法可以监视导出函数的模块,例如execa
在给定的例子中?
我有完全相同的需求和问题execa
,这就是我如何让它发挥作用的:
import execa from 'execa'
jest.mock('execa', () => jest.fn())
test('it calls execa', () => {
runSomething()
expect(execa).toHaveBeenCalled()
})
所以基本上,由于导入的模块是函数本身,所以你所做的就是模拟整个模块jest.mock
,并简单地返回一个 Jest 模拟函数作为其替换。
Since jest.fn()
是什么jest.spyOn()
依赖于底层,您可以从测试中相同的断言方法中受益:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)