如何使用Jest监视默认的导出功能? [英] How to spy on a default exported function with Jest?

查看:126
本文介绍了如何使用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 do this in a clean way? There's a similar GitHub issue for jasmine for anyone interested.

推荐答案

仍然可以接受建议,但是我所做的却是放弃了默认的导出:

Still open to suggestions but what I did was 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆