Jasmine: 如何在ES6中监视导入的函数/构造函数?

10

我想知道在使用ES6的import和export以及babel的情况下,如何在Jasmine上进行函数的间谍/存根?

import MobileDetect from 'mobile-detect';
it('should spy MobileDetect', () => {
    MobileDetect = jasmine.createSpy('MobileDetect');
});`

第一个问题是我无法重写只读模块

模块构建失败:SyntaxError:/Users/oleg/projects/rp/popup/lib/spec/popup.spec.js:"MobileDetect" 是只读的

it('should spy MobileDetect', () => {
    console.log(MobileDetect.prototype.constructor === MobileDetect); //true
    spyOn( MobileDetect.prototype, 'constructor' );
    console.log(MobileDetect.prototype.constructor === MobileDetect); //false
});`

我尝试了这种方法,但它也不起作用... MobileDetect.prototype.constructor被窥视,但MobileDetect直接没有。

你对这个问题有什么看法?


你不能窥探MobileDetect,因为变量的值无法重写为新的窥探函数。我的猜测是:如果你这样做var myMobileDetect = MobileDetect,然后窥探myMobileDetect呢?显然,你需要改变你的代码来使用myMobileDetect - apsillers
2
我想知道你在测试中想要实现什么。你是想创建一个模拟MobileDetect方法的间谍吗?(即一个模拟对象) - Bobby Matson
1个回答

1
proxyquire 相似,用于在测试中模拟 require() 语句的,您可以使用 babel-plugin-rewire 来处理 ES6 导入。

您的测试设置可能如下所示;

import myModuleUnderTest from '../src/popup';

beforeEach(() => {
    this.fakeMobileDetect = jasmine.createSpy();
    myModuleUnderTest.__Rewire__('MobileDetect', this.fakeMobileDetect);
});

你可以使用以下代码将其恢复为正常状态:
afterEach(() => {
    myModuleUnderTest.__ResetDependency__('MobileDetect');
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接