Jest 模拟节点模块不使用打字稿

Jest mock node module not working with typescript

我尝试模拟来自 npm 的模块 uuid/v4。 为此,我按照 jest 的建议创建了一个模拟文件夹:https://jestjs.io/docs/en/manual-mocks

我的文件夹结构:

├──__mocks__ 
|  └──uuid
|       └──v4.ts
├──src
│   └──__tests__
│   └── ...
├──node_modules

模拟节点模块文件 v4.ts :

module.exports = jest.fn();

当我尝试在我的测试文件中导入 uuid/v4 时,jest 通常应该导入模拟并且我应该能够使用它。

这是我的测试文件:

import uuidv4 from 'uuid/v4';

it('should create a job', () => {
    const jobId = 'fake-job-id';
    uuidv4.mockReturnValue(jobId); 
    ...
}

不幸的是,模拟导入似乎不起作用,因为我无法添加 jest 提供的 mockReturnValue 并且出现以下打字稿错误: property 'mockReturnValue' does not exist on type v4. ts(2339)

你知道我该如何解决这个问题吗?提前致谢。

处理这种情况的一种常见方法是在测试中自动模拟模块,然后使用 jest.Mocked 告诉 TypeScript 模块是自动模拟的,如下所示:

jest.mock('uuid/v4');  // <= auto-mock uuid/v4

import uuidv4 from 'uuid/v4';
const mocked = uuidv4 as jest.Mocked<typeof uuidv4>;  // <= tell TypeScript it's an auto-mock

test('hi', () => {
  mocked.mockReturnValue('mocked result');  // <= use the properly typed mock
  expect(uuidv4()).toBe('mocked result');  // Success!
})

不幸的是,uuid/v4 的输入似乎不适用于这种方法。

作为解决方法,您可以使用类型断言:

jest.mock('uuid/v4');  // <= auto-mock uuid/v4

import uuidv4 from 'uuid/v4';

test('hi', () => {
  (uuidv4 as jest.Mock).mockReturnValue('mocked result');  // <= use a type assertion
  expect(uuidv4()).toBe('mocked result');  // Success!
})