如何使用 Jest 监视默认的导出函数? [英] How to spy on a default exported function with Jest?
问题描述
假设我有一个导出默认函数的简单文件:
Suppose I have a simple file exporting a default function:
// UniqueIdGenerator.js
const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);
export default uniqueIdGenerator;
我会像这样使用:
import uniqueIdGenerator from './UniqueIdGenerator';
// ...
uniqueIdGenerator();
我想在我的测试中断言在保持原始功能的同时调用了这个方法.我会用 jest.spyOn
但是,它需要一个对象以及一个函数名称作为参数.你怎么能以干净的方式做到这一点?对于任何感兴趣的人,jasmine
都有一个类似的 GitHub 问题.
I want to assert in my test that this method was called while keeping the original functionality. I'd do that with jest.spyOn
however, it requires an object as well as a function name as parameters. How can you do this in a clean way? There's a similar GitHub issue for jasmine
for anyone interested.
推荐答案
我最终放弃了默认导出:
I ended up ditching the default export:
// UniqueIdGenerator.js
export const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);
然后我可以像这样使用和监视它:
And then I could use and spy it like this:
import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'uniqueIdGenerator');
有些人推荐将它们包装在一个 const 对象中,并出口.我想你也可以使用一个类来包装.
Some recommend wrapping them in a const object, and exporting that. I suppose you can also use a class for wrapping.
但是,如果您不能修改类,仍然有一个(不太好的)解决方案:
However, if you can't modify the class there's still a (not-so-nice) solution:
import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'default');
这篇关于如何使用 Jest 监视默认的导出函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!