问题:
有人会帮我弄清楚如何使用打字稿开玩笑地模拟 fs 吗?我已经尝试了一些东西,这是主要的:
我正在尝试使用 jest 来模拟“fs”,但我似乎无法让 jest 在 Typescript 中自动模拟“fs”库。
这是我的代码:
import fs from 'fs';
jest.mock('fs');
describe('helloWorld.ts', () => {
it('foobar', () => {
fs.readdirSync.mockReturnValue(['foo.js', 'bar.js']);
})
});
打字稿告诉我“类型上不存在属性'mockReturnValue'......”
环境:
节点 v14.15.1
打字稿:“^4.0.3”
VS 代码打字稿:4.1.2
在相关的说明中,我用 spyOn 尝试了这个,但失败了:
我尝试使用它但也无法spyOn
工作(参考: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('.'));
});
});
此代码失败并出现此打字稿错误 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'.
相关参考:
- 这似乎是相关的,但我觉得有一个更好的解决方案:Mock 'fs' module in jest
- 玩笑在这里有一个问题,表明在使用
jest.mock('fs')
https://github.com/facebook/jest/issues/2258明确模拟时,模拟“fs”应该起作用