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

1

10

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?

Jennyjeno answered 1/3, 2016 at 12:46 Comment(2)
You can't spy on MobileDetect because the variable's value can't be rewritten to a new spying function. My guess: what if you did var myMobileDetect = MobileDetect and then spied on myMobileDetect instead? Obviously, you'd need to change your code to use myMobileDetect, though.Zacatecas
I'm wondering what you are trying to accomplish in your test. Are you looking to create a spy that mimics MobileDetect's methods? (ie a mock)Somersomers
H
1

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');
});
Hautegaronne answered 22/2, 2017 at 16:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.