【发布时间】:2019-12-28 08:37:16
【问题描述】:
在Jest 中,为了监视(并可选择模拟实现)方法,我们执行以下操作:
const childProcess = require('child_process');
const spySpawnSync = jest.spyOn(childProcess, 'spawnSync').mockImplementation();
这允许我们使用spySpawnSync 来检查上次调用它时使用的参数,如下所示:
expect(spySpawnSync).lastCalledWith('ls');
但是,这对于导出函数的 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');
因此,有没有办法监视导出函数的模块,例如给定示例中的execa?
【问题讨论】:
标签: node.js unit-testing mocking jestjs spy