无法使用打字稿开玩笑地模拟 fs - 类型

时间:2021-01-25 19:50:16

标签: typescript jestjs ts-jest automocking

问题:

有人能帮我弄清楚如何使用打字稿开玩笑地模拟 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'...”

cannot mock fs with jest

环境:

节点 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'.

相关参考资料:

1 个答案:

答案 0 :(得分:1)

TypeScript 编译器对 fs 是一个模拟一无所知。

您可以使用 type assertion 告诉它:

(<jest.Mock>fs.readdirSync).mockReturnValue(...);

每次使用从 fs 模块导入的模拟函数时,执行此操作都会变得乏味。为了使事情更简单,您可以声明一个类型为模块模拟的变量,使用 fs 对其进行初始化并在测试中使用它而不是 fs

import fs from 'fs';

jest.mock('fs');

const mockFS: jest.Mocked<typeof fs> = <jest.Mocked<typeof fs>>fs;

describe('helloWorld.ts', () => {
  it('foobar', () => {

    mockFS.readdirSync.mockReturnValue(['foo.js', 'bar.js']);
  });
});