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

I am wondering how can I use the spy / stub function on Jasmine if I use ES6 import / export with babel?

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

The first problem is that I cannot rewrite a read-only module

Module build error: 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 either ... MobileDetect.prototype.constructor is a spy, but MobileDetect does not work directly.

What do you think of this problem?

+8
javascript ecmascript-6 jasmine spy es6-module-loader
source share
1 answer

Like proxyquire for require() bullying in your tests, you can use babel-plugin-rewire to do the same with ES6 import.

Your test setup might look something like this:

 import myModuleUnderTest from '../src/popup'; beforeEach(() => { this.fakeMobileDetect = jasmine.createSpy(); myModuleUnderTest.__Rewire__('MobileDetect', this.fakeMobileDetect); }); 

What you can return to normal with:

 afterEach(() => { myModuleUnderTest.__ResetDependency__('MobileDetect'); }); 
+1
source share

All Articles