問題:
typescript を使用して jest で fs をモックする方法を誰かが教えてくれますか? 私はいくつかのことを試しましたが、主なものは次のとおりです。
jest を使用して 'fs' をモックしようとしていますが、Typescript で jest に 'fs' ライブラリを自動モック化させることができないようです。
これが私のコードです:
import fs from 'fs';
jest.mock('fs');
describe('helloWorld.ts', () => {
it('foobar', () => {
fs.readdirSync.mockReturnValue(['foo.js', 'bar.js']);
})
});
Typescript は、「プロパティ 'mockReturnValue' は型に存在しません...」と教えてくれます
環境:
Node v14.15.1 Typescript
: "^4.0.3"
VS Code Typescript: 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('.'));
});
});
このコードは、次の typescript エラー 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 には、 https://github.com/facebook/jest/issues/2258で明示的にモックされた場合に「fs」のモックが機能することを示唆する問題があります。
jest.mock('fs')