Problem:
Would someone help me figure out how to mock fs with jest using typescript? I've tried a few things, and here is the main one:
I'm attempting to use jest to mock 'fs', but I can't seem to get jest to automock the 'fs' library in Typescript.
Here is my code:
import fs from 'fs';
jest.mock('fs');
describe('helloWorld.ts', () => {
it('foobar', () => {
fs.readdirSync.mockReturnValue(['foo.js', 'bar.js']);
})
});
Typescript tells me "Property 'mockReturnValue' does not exist on type..."
Environment:
Node v14.15.1
Typescript: "^4.0.3"
VS Code Typescript: 4.1.2
On a related note, I tried this with spyOn and it failed:
I tried to use this but couldn't get spyOn
to work either (reference: jest typescript property mock does not exist on type )
import fs from 'fs';
describe('helloWorld.ts', () => {
it('foobar', () => {
jest.spyOn(fs, 'readdirSync').mockImplementation(() => {
return ['foo.js', 'bar.js'];
});
console.log(fs.readdirSync('.'));
});
});
This code fails with this typescript error TS2345:
Argument of type '() => string[]' is not assignable to parameter of type '(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true; }) => Dirent[]'.
Type 'string[]' is not assignable to type 'Dirent[]'.
Type 'string' is not assignable to type 'Dirent'.
Related references:
- This appears to be related, but I feel there's a better solution: Mock 'fs' module in jest
- Jest has an issue here that suggests that mocking 'fs' should work when explicitly mocked with
jest.mock('fs')
https://github.com/facebook/jest/issues/2258