Feb 7, 2020

Jest Mock in TypeScript

Writing tests in TypeScript in quite painful, especially when using mock.

import { readFile } from './fs-util';

jest.mock('./fs-util');

(readFile as jest.MockInstance).mockImplementation((path: string) => {
  // mock implementation
});

If you’re using ts-jest (which you probably already are if you write your tests in TypeScript), it provides a mocked helper.

import { mocked } from 'ts-jest/utils';
import { readFile } from './fs-util';

jest.mock('./fs-util');

mocked(readFile).mockImplementation((path) => {
  // mock implementation
});