Search code examples
webpackjasminebabeljs

import * as (jasmine spyOn) not writable


After upgrading to babel 7.1.5 my tests fail when i'm using import * as.

test.spec.js

import * as Helper from "../../../../src/renderer/modules/Helper";

describe('Testing', () => {
    it('Should import correctly', () => {
        console.log(Helper.test()) // a
        spyOn(Helper, 'test').and.returnValue('b');
    });
});

Helper.js

function test() {
    return 'a'
}

export {test}

ERROR

'Upgrade.spec.js (7:8)', 'a'

Error: <spyOn> : test is not declared writable or has no setter
Usage: spyOn(<object>, <methodName>)
    at <Jasmine>
    at UserContext.it (webpack:///./test/unit/specs/renderer/Upgrade.spec.js?:7:5)
    at <Jasmine>

Solution

  • source: Can webpack 4 modules be configured as to allow Jasmine to spy on their members?

    There's spyOnProperty which allows treating a property as read-only by setting the accessType argument to 'get'.

    Your setup would then look like

    import * as mod from 'my/module';
    //...
    const funcSpy = jasmine.createSpy('myFunc').and.returnValue('myMockReturnValue');
    spyOnProperty(mod, 'myFunc', 'get').and.returnValue(funcSpy);