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:
readFile as jest.Mock<{}>
Could a TypeScript plugin perform the module augmentation when modules are required by jest.mock
?
simplest solution is to import fs like this: const fs = require('fs')
, and use (fs.readFile as jest.Mock).mockImplementationOnce ...
Simple solution is to import directly from the mock file. It looks inelegant, but works.
import { readFile } from '../__mocks__/fs';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With