node.js - 你如何用 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)
解决方案
推荐阅读
- javascript - Firestore 基于 orderBy 和限制从集合中检索单个文档,而不使用 forEach
- angular - 每当左键单击节点时提示自定义上下文菜单
- c++ - 我应该在没有有意义的恢复的情况下捕获异常吗?
- autofac - 如何在 Autofac 中获取已注册服务的列表
- c++ - 访问与父类是朋友的类的私有成员
- c# - 代码中添加到面板的标签控件不显示
- azure - 使用 terraform 创建 azure webhook
- c - 客户端发送消息但在服务器上看不到
- tensorflow - TensorFlow Objection Detection API 训练错误
- json - 使用 perl 在 bash 中将 yaml 转换为 json