node.js - 我如何开玩笑地模拟链式函数?
问题描述
我用 jest 来测试我的 node.js 代码。我需要使用 mongoose 连接到 mongodb。但我不知道如何模拟链式函数。
我需要模拟的功能(容器是一个模块):
return await Vessels.find({}).exec();
我试图模拟的方式,但它失败了:
Vessels.find.exec = jest.fn(() => [mockVesselResponse]);
我想模拟链式函数Vessels.find({}).exec()
,这里的任何人都可以帮助我,谢谢。
解决方案
天真的方法是模拟方法find
,该方法将返回带有方法的对象(有关详细信息,请查看有关模拟模块的方法的exec
Jest 文档):
import Vessels from '/path/to/vessels';
jest.mock('/path/to/vessels');
Vessels.prototype.find.mockReturnThis();
Vessels.prototype.exclude.mockReturnThis();
Vessels.prototype.anyOtherChainingCallMethod.mockReturnThis();
it('your test', () => {
Vessels.prototype.exec.mockResolvedValueOnce([youdata]);
// your code here
});
但在我看来,模拟每一个内部方法需要大量手动工作。
相反,我建议你更深一层地嘲笑。用mongoose
模拟模型说mockingoose
.
从未使用过,mongoose
因此无法为这种方法提供样本。
推荐阅读
- jquery - jquery - 在点击事件回调中获取 $(this) 选中单选选项的值
- angular - 为什么我不能从我的 Gorilla WebSocket 服务器读取消息,直到它被客户端关闭?
- java - 如何在基于操作系统的 java 中获取获取周期的结果?我是java的新手我正在寻找一些建议
- json - 我正在尝试在应用程序网页上滚动,但似乎无法正常工作
- exception - DNN API 控制器 - 任务已取消日志
- html - 未捕获的 ReferenceError:未定义 Swiper
- node.js - TypeError:无效的架构配置:`model` 不是数组`category` 中的有效类型
- ubuntu - 我试图为我的虚拟机添加额外的空间。我从 250GB 增加到 +750GB,但无法将其添加到 lvm
- java - 存储 aes 加密数据的最佳方式
- laravel - Laravel 8,Jetstream中LOGIN模型的文件在哪里