繁体   English   中英

Jasmine:如何在ES6上窥探导入的函数/构造函数?

[英]Jasmine: How to spy imported function/constructor on ES6?

我想知道如果我使用ES6导入/导出与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" is read-only

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不直接。

你怎么看待这个问题?

与您的测试中的mocking require()语句的proxyquire类似,您可以使用babel-plugin-rewire对ES6导入执行相同的操作。

您的测试设置可能看起来像这样;

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

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

你可以恢复正常;

afterEach(() => {
    myModuleUnderTest.__ResetDependency__('MobileDetect');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM