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 the test suite.
An example could be the official one from the Jest documentation (https://jestjs.io/docs/en/es6-class-mocks#manual-mock). There the SoundPlayer
class has been mocked, as it is its only method playSoundFile
. The method is mocked using a jest.fn()
, which is exported to be used in tests.
// soundPlayer.ts
export default class SoundPlayer {
foo: string = 'bar';
playSoundFile(filename: string) {
console.log(`Playing sound file ${filename}`);
}
}
// __mocks__/soundPlayer.ts
export const mockPlaySoundFile = jest.fn();
const mock = jest.fn().mockImplementation(() => {
return { playSoundFile: mockPlaySoundFile };
});
export default mock;
// __tests__/soundPlayer.ts
import SoundPlayer, { mockPlaySoundFile } from '../soundPlayer';
jest.mock('../soundPlayer');
beforeEach(() => {
mockPlaySoundFile.mockClear();
});
it('is called with filename', () => {
const filename = 'song.mp3';
const soundPlayer = new SoundPlayer();
soundPlayer.playSoundFile(filename);
expect(mockPlaySoundFile).toBeCalledWith(filename);
});
The test works as expected, but TS notifies an error (which kind of makes sense to me) when trying to import the mocked mockPlaySoundFile
function. That is because, obviously, mockPlaySoundFile
doesn't exist in soundPlayer.ts
. But because of jest.mock('../soundPlayer');
the mock is imported under the hood, therefore the export does exist.
Is there a way to inform TS to look at the mocks in cases like this?
mocked
helper from ts-jest: github.com/kulshekhar/ts-jest/blob/master/docs/user/… – Tobi