我有以下模块我试图在Jest中测试:
// myModule.js
export function otherFn() {
console.log('do something');
}
export function testFn() {
otherFn();
// do other things
}
Run Code Online (Sandbox Code Playgroud)
如上图所示,这部分出口命名的功能和重要的testFn
用途otherFn
.
在Jest中我正在编写单元测试时testFn
,我想模拟该otherFn
函数,因为我不希望错误otherFn
影响我的单元测试testFn
.我的问题是我不确定最好的方法:
// myModule.test.js
jest.unmock('myModule');
import { testFn, otherFn } from 'myModule';
describe('test category', () => {
it('tests something about testFn', () => {
// I want to mock "otherFn" here but can't reassign
// a.k.a. can't do otherFn = jest.fn()
});
});
Run Code Online (Sandbox Code Playgroud)
任何帮助/见解表示赞赏.
我有一个带有功能的模块:
const utils = {
redirectTo(url) {
if (url) {
window.location = url;
}
},
};
export default utils;
Run Code Online (Sandbox Code Playgroud)
它在React组件的某处使用,如下所示:
import utils from '../../lib/utils';
componentWillUpdate() {
this.redirectTo('foo')
}
Run Code Online (Sandbox Code Playgroud)
现在,我要检查redirectTo
用equals调用的值foo
。
it('should redirect if no rights', () => {
const mockRedirectFn = jest.fn();
utils.redirectTo = mockRedirectFn;
mount(
<SomeComponent />,
);
expect(mockRedirectFn).toBeCalled();
expect(mockRedirectFn).toBeCalledWith('foo');
console.log(mockRedirectFn.mock);
// { calls: [], instances: [] }
});
Run Code Online (Sandbox Code Playgroud)
那就是我所拥有的,它不起作用。我该怎么做呢?
在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
在给定的示例中?
jestjs ×3
unit-testing ×3
ecmascript-6 ×1
javascript ×1
mocking ×1
node.js ×1
reactjs ×1
spy ×1