Import function from a Jest manual mock with Typescript

前端 未结 2 1219
[愿得一人]
[愿得一人] 2021-01-03 02:09

I\'m creating a custom mock (of an ES6 class) with Jest in a Typescript project. The mock creates end exports a few mock.fn() so that they could be spied on in

2条回答
  •  鱼传尺愫
    2021-01-03 03:04

    The easiest way to fix this is to use ts-jest's mocked() helper. The helper will make sure you have access to the mock test methods. __tests__/soundPlayer.ts would then look as follows:

    // __tests__/soundPlayer.ts
    import { mocked } from "ts-jest/utils";
    import SoundPlayer from '../soundPlayer';
    
    jest.mock('../soundPlayer');
    
    const soundPlayer = mocked(new SoundPlayer());
    
    beforeEach(() => {
      soundPlayer.playSoundFile.mockClear();
    });
    
    it('is called with filename', () => {
      const filename = 'song.mp3';
    
      soundPlayer.playSoundFile(filename);
    
      expect(soundPlayer.playSoundFile).toBeCalledWith(filename);
    });
    

    If you really want to include mockPlaySoundFile you could do it by telling the Typescript compiler to suppresses the import error:

    // @ts-ignore
    import { mockPlaySoundFile } from '../soundPlayer';
    

    Also, have a look at the example in my repo here: https://github.com/tbinna/ts-jest-mock-examples, in particular, your soundPlayer example: https://github.com/tbinna/ts-jest-mock-examples/tree/master/sound-player

提交回复
热议问题