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:
question from:
https://stackoverflow.com/questions/65891484/cannot-mock-fs-with-jest-using-typescript-property-mockreturnvalue-does-not 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…