首页 > 解决方案 > 你如何用 Jest 模拟一个外部 npm 模块?

问题描述

我正在尝试模拟测试文件中未引用的 npm 模块。我看到的大多数答案都是在测试文件中创建模拟,然后也从测试文件中引用。这不是我想要做的。

我希望我的测试模拟一个 npm 模块,并具有testMe尝试从被模拟的模块调用代码并从中接收模拟数据的功能。出于某种原因,这被证明是难以捉摸的。

image.ts

import Jimp from "jimp/es";

export const testMe = async (string: string) => {
  const res = await Jimp.read(string);

  return res;
}

image.test.ts

import { testMe } from '../src/utils/image';

jest.mock('jimp/es', () => ({
  read: jest.fn(() => Promise.resolve('mockedString'))
}));

describe('testMe', () => {
  it('successfully completes', async () => {
    const image = 'abcde==';

    const result = await testMe(image);

    expect(result).toBe('mockedString');
  });
});

我应该如何构建测试文件以正确模拟依赖项?目前,我只收到以下错误:

  ● testMe › successfully completes

    TypeError: Cannot read property 'read' of undefined

      21 | 
      22 | export const testMe = async (string: string) => {
    > 23 |   const res = await Jimp.read(string);
         |                          ^
      24 | 
      25 |   return res;
      26 | }

      at Object.exports.testMe (src/utils/image.ts:23:26)
      at Object.<anonymous> (__tests__/image.test.ts:26:26)

标签: node.jsunit-testingjestjs

解决方案


推荐阅读