1

问题:

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

不能用玩笑来模拟 fs

环境:

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

相关参考:

4

1 回答 1

1

TypeScript 编译器不知道任何关于fs模拟的事情。

您可以通过使用类型断言来告诉它:

(<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']);
  });
});
于 2021-01-25T19:57:55.797 回答