Reactjs 如何使用Jest监视默认导出函数?
假设我有一个导出默认函数的简单文件:Reactjs 如何使用Jest监视默认导出函数?,reactjs,unit-testing,mocking,jestjs,spy,Reactjs,Unit Testing,Mocking,Jestjs,Spy,假设我有一个导出默认函数的简单文件: // UniqueIdGenerator.js const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8); export default uniqueIdGenerator; 我会这样使用它: import uniqueIdGenerator from './UniqueIdGenerator'; // ... uniqueIdGenerator(); i
// UniqueIdGenerator.js
const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);
export default uniqueIdGenerator;
我会这样使用它:
import uniqueIdGenerator from './UniqueIdGenerator';
// ...
uniqueIdGenerator();
import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'uniqueIdGenerator');
我想在测试中断言,调用此方法时保留了原始功能。不过,它需要一个对象和一个函数名作为参数。你怎么能以一种干净的方式做到这一点?对任何感兴趣的人来说,
jasmine
都有类似的功能。我最终放弃了默认导出:
// UniqueIdGenerator.js
export const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);
import * as fetch from 'node-fetch'
jest.mock('node-fetch', () => ({
default: jest.fn(),
}))
jest.spyOn(fetch, 'default')
然后我可以像这样使用和监视它:
import uniqueIdGenerator from './UniqueIdGenerator';
// ...
uniqueIdGenerator();
import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'uniqueIdGenerator');
将它们包装到一个const对象中,并将其导出。我想你也可以用一个类来包装
但是,如果您不能修改该类,仍然有一个(不太好的)解决方案:
import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'default');
在某些情况下,您必须模拟导入才能监视默认导出:
// UniqueIdGenerator.js
export const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);
import * as fetch from 'node-fetch'
jest.mock('node-fetch', () => ({
default: jest.fn(),
}))
jest.spyOn(fetch, 'default')
还可以模拟导入并将原始实现作为模拟实现传递,如:
import uniqueIdGenerator from './UniqueIdGenerator'; // this import is a mock already
jest.mock('./UniqueIdGenerator.js', () => {
const original = jest. requireActual('./UniqueIdGenerator')
return {
__esModule: true,
default: jest.fn(original.default)
}
})
test(() => {
expect(uniqueIdGenerator).toHaveBeenCalled()
})
对我来说,有效的方法是将来自和OP自己的解决方案的答案结合起来。我想要测试的是,helper方法是用正确的参数调用的,因为我已经为helper方法编写了一个测试,它对我的后续测试没有任何影响:
// myHelperMethod.js
export const myHelperMethod = (param1, param2) => { // do something with the params };
//使用MyHelperMethod.js的其他文件
从“../MyHelperMethod”导入*作为MyHelperMethod;
jest.mock(“../myHelperMethod”,()=>({
myHelperMethod:jest.fn(),
}));
让myHelperMethodSpy=jest.spyOn(MyHelperMethod,'MyHelperMethod');
// ...
//一些设置
// ...
测试(()=>{
expect(myHelperMethodSpy).已通过(param1,param2)调用;
});
但这只有在babel通过es6模块传输时才起作用。在CommonJSDownvoted上不起作用,因为它没有解决原始问题的关键——如何使用默认导出——尽管OP自己在自己接受的答案中选择放弃默认导出,但这是另一个问题。所以不是这样的