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?

edi9999
  • 19,701
  • 13
  • 88
  • 127
dedirot
  • 101
  • 1
  • 4
  • 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. – apsillers Mar 01 '16 at 13:26
  • 2
    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) – Bobby Matson Mar 01 '16 at 13:42

1 Answers1

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');
});
Jamie Mason
  • 4,159
  • 2
  • 32
  • 42