8

When I compile my a test using the TypeScript compiler and working with a Jest mock, I often receive errors from tsc like:

error TS2339: Property 'mockImplementationOnce' does not exist on type
              'typeof readFile'.

from this minimal test:

jest.mock('fs');
// Run before the imports but does not alter types :(

import { readFile } from 'fs';
import { fnThatReadsFile } from './lib';

it('should read a file', () => {
  const err = {};
  readFile.mockImplementationOnce((_, callback) => callback(err, null));
  // ^^ error TS2339: Property 'mockImplementationOnce' does not exist on type 'typeof readFile'.

  fnThatReadsFile();
  // expect...
});


What solutions are there other than:

Could a TypeScript plugin perform the module augmentation when modules are required by jest.mock?

Sean
  • 1,279
  • 9
  • 17

2 Answers2

9

simplest solution is to import fs like this: const fs = require('fs'), and use (fs.readFile as jest.Mock).mockImplementationOnce ...

Herman Starikov
  • 2,636
  • 15
  • 26
  • Thanks Herman. I've found that casting is the most verbose way to work since you need to cast it every time you're working with it. – Sean May 22 '18 at 21:42
3

Simple solution is to import directly from the mock file. It looks inelegant, but works.

import { readFile } from '../__mocks__/fs';
pavloko
  • 970
  • 9
  • 8