首页 > 解决方案 > 我如何开玩笑地模拟链式函数?

问题描述

我用 jest 来测试我的 node.js 代码。我需要使用 mongoose 连接到 mongodb。但我不知道如何模拟链式函数。

我需要模拟的功能(容器是一个模块):

return await Vessels.find({}).exec();

我试图模拟的方式,但它失败了:

 Vessels.find.exec = jest.fn(() => [mockVesselResponse]);

我想模拟链式函数Vessels.find({}).exec(),这里的任何人都可以帮助我,谢谢。

标签: node.jsunit-testingmongoosejestjs

解决方案


天真的方法是模拟方法find,该方法将返回带有方法的对象(有关详细信息,请查看有关模拟模块的方法的execJest 文档):

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因此无法为这种方法提供样本。


推荐阅读