Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am wondering how can I spy/stub function on Jasmine if I am using ES6 imports/exports with babel?

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

The first problem is that I can't rewrite read-only module

Module build failed: 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
});`

I tried this approach, but it doesn't work too... MobileDetect.prototype.constructor spied, but MobileDetect directly not.

What do you think about this problem?

like image 492
dedirot Avatar asked Mar 01 '16 12:03

dedirot


1 Answers

Similar to proxyquire for mocking require() statements in your tests, you can use babel-plugin-rewire to do the same with ES6 imports.

Your test setup might look something like this;

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

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

Which you can revert to normal with;

afterEach(() => {
    myModuleUnderTest.__ResetDependency__('MobileDetect');
});
like image 164
Jamie Mason Avatar answered Oct 12 '22 23:10

Jamie Mason