【问题标题】:Jest mock node module not working with typescript开玩笑的模拟节点模块不适用于打字稿
【发布时间】:2020-01-07 08:11:32
【问题描述】:

我尝试模拟来自 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)

您知道我该如何解决吗?提前致谢。

【问题讨论】:

    标签: typescript unit-testing mocking jestjs ts-jest


    【解决方案1】:

    处理这种情况的常用方法是在测试中自动模拟模块,然后使用 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!
    })
    

    【讨论】:

    • 谢谢布赖恩,它工作得很好!我注意到它也适用于:jest.mock('uuid/v4'); const uuidv4 = require('uuid/v4'); ,不需要类型断言。
    • 太棒了,很高兴听到!是的,使用jest.Mocked 是理想的,因为它保持了类型安全,但由于在这种情况下类型断言(某种类型安全)或const uuidv4 = require('uuid/v4');uuidv4 是类型any)工作不正常很好的解决方法。
    猜你喜欢
    • 2021-12-09
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    相关资源
    最近更新 更多