How can I mock the imports of an ES6 module?

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

    I have found this syntax to be working:

    My module:

    // File mymod.js
    import shortid from 'shortid';
    
    const myfunc = () => shortid();
    export default myfunc;
    

    My module's test code:

    // File mymod.test.js
    import myfunc from './mymod';
    import shortid from 'shortid';
    
    jest.mock('shortid');
    
    describe('mocks shortid', () => {
      it('works', () => {
        shortid.mockImplementation(() => 1);
        expect(myfunc()).toEqual(1);
      });
    });
    

    See the documentation.

提交回复
热议问题