Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jest.mock and TypeScript without cluttered type casting?

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:

  • casting: readFile as jest.Mock<{}>
  • module augmentation

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

like image 907
Sean Avatar asked May 06 '18 04:05

Sean


2 Answers

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

like image 131
Herman Starikov Avatar answered Nov 02 '22 04:11

Herman Starikov


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

import { readFile } from '../__mocks__/fs';
like image 21
pavloko Avatar answered Nov 02 '22 04:11

pavloko