How can I mock the imports of an ES6 module?

后端 未结 8 1583
醉话见心
醉话见心 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:37

    vdloo's answer got me headed in the right direction, but using both CommonJS "exports" and ES6 module "export" keywords together in the same file did not work for me (Webpack v2 or later complains).

    Instead, I'm using a default (named variable) export wrapping all of the individual named module exports and then importing the default export in my tests file. I'm using the following export setup with Mocha/Sinon and stubbing works fine without needing rewire, etc.:

    // MyModule.js
    let MyModule;
    
    export function myfunc2() { return 2; }
    export function myfunc1() { return MyModule.myfunc2(); }
    
    export default MyModule = {
      myfunc1,
      myfunc2
    }
    
    // tests.js
    import MyModule from './MyModule'
    
    describe('MyModule', () => {
      const sandbox = sinon.sandbox.create();
      beforeEach(() => {
        sandbox.stub(MyModule, 'myfunc2').returns(4);
      });
      afterEach(() => {
        sandbox.restore();
      });
      it('myfunc1 is a proxy for myfunc2', () => {
        expect(MyModule.myfunc1()).to.eql(4);
      });
    });
    

提交回复
热议问题