How can I mock the imports of an ES6 module?

后端 未结 8 1586
醉话见心
醉话见心 2020-11-28 21:33

I have the following ES6 modules:

File network.js

export function getDataFromServer() {
  return ...
}

File widget.js<

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 21:43

    carpeliam is correct, but note that if you want to spy on a function in a module and use another function in that module calling that function, you need to call that function as part of the exports namespace, otherwise the spy won't be used.

    Wrong example:

    // File mymodule.js
    
    export function myfunc2() {return 2;}
    export function myfunc1() {return myfunc2();}
    
    // File tests.js
    import * as mymodule
    
    describe('tests', () => {
        beforeEach(() => {
            spyOn(mymodule, 'myfunc2').and.returnValue = 3;
        });
    
        it('calls myfunc2', () => {
            let out = mymodule.myfunc1();
            // 'out' will still be 2
        });
    });
    

    Right example:

    export function myfunc2() {return 2;}
    export function myfunc1() {return exports.myfunc2();}
    
    // File tests.js
    import * as mymodule
    
    describe('tests', () => {
        beforeEach(() => {
            spyOn(mymodule, 'myfunc2').and.returnValue = 3;
        });
    
        it('calls myfunc2', () => {
            let out = mymodule.myfunc1();
            // 'out' will be 3, which is what you expect
        });
    });
    

提交回复
热议问题