javascript 如何监视默认导出的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32891606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:52:38  来源:igfitidea点击:

How to spy on a default exported function

javascriptnode.jssinon

提问by reza

sinon.spy takes 2 parameters, object and function name.

sinon.spy 有两个参数,对象和函数名。

I have a module as listed below:

我有一个如下所列的模块:

module.exports = function xyz() { }

module.exports = function xyz() { }

How do I define a spy for xyz? I don't have object name to use.

我如何定义间谍xyz?我没有要使用的对象名称。

Thoughts?

想法?

回答by Benjamin Hughes

The above actually doesn't work if you're using the ES6 modules import functionality, If you are I've discovered you can actually spy on the defaults like so.

如果您使用 ES6 模块导入功能,上述实际上不起作用,如果您是,我发现您实际上可以像这样监视默认值。

// your file
export default function () {console.log('something here');}

// your test
import * as someFunction from './someFunction';
spyOn(someFunction, 'default')

As stated in http://2ality.com/2014/09/es6-modules-final.html

http://2ality.com/2014/09/es6-modules-final.html 所述

The default export is actually just a named export with the special name default

默认导出实际上只是一个带有特殊名称 default 的命名导出

So the import * as someFunction gives you access to the whole module.exports object allowing you to spy on the default.

因此 import * as someFunction 使您可以访问整个 module.exports 对象,从而允许您监视默认值。