javascript 如何使用 Jasmine 监视通过 ES6 默认导出导入的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34113145/
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
How do I use Jasmine to spy on a function that is imported via an ES6 default export?
提问by evkline
I am working on a Redux app & trying to create a spy using Jasmine on an ES6 default exported function. I have attempted a few different ways of spying on the function, including using a wildcard import to access the 'default' property of the import, but nothing I've tried has worked thus far. Below is an example, where I would want to test widgets.js
and spy on the widget function. Is there a way to achieve this without having to change the way im exporting the function from widget.js
?
我正在开发一个 Redux 应用程序并尝试在 ES6 默认导出函数上使用 Jasmine 创建一个间谍。我尝试了几种不同的监视函数的方法,包括使用通配符导入来访问导入的“默认”属性,但到目前为止我尝试过的任何方法都没有奏效。下面是一个示例,我想在其中测试widgets.js
和监视小部件功能。有没有一种方法可以实现这一点,而不必更改我从中导出函数的方式widget.js
?
widget.js
小部件.js
import { Map } from 'immutable';
import { CREATE_WIDGET } from 'actions';
const initialState = Map({
id: undefined,
name: undefined
});
export default function widget(state=initialState, action) {
switch (action.type) {
case CREATE_WIDGET:
return state.update((widget) => widget.merge(action.widget));
default:
return state;
}
}
widgets.js
小部件.js
import { OrderedMap } from 'immutable';
import { CREATE_ROOM } from 'actions';
import widget from './widget';
const initialState = OrderedMap();
export default function widgets(state=initialState, action={}) {
switch (action.type) {
case CREATE_ROOM:
return state.set(action.widget.id, widget(undefined, action));
default:
return state;
}
}
回答by jdrush89
You say you tried importing the wildcard and spying on default? What was the issue with that approach? I just ran into this problem and doing this solved it for me:
您说您尝试导入通配符并监视默认值?这种方法有什么问题?我刚刚遇到了这个问题,这样做为我解决了这个问题:
import * as widget from './widget';
describe('widget spec', () => {
beforeEach(() => {
spyOn(widget, 'default');
});
});