【问题标题】:How do I mock chained function in jest?我如何开玩笑地模拟链式函数?
【发布时间】:2019-11-17 16:56:30
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: node.js unit-testing mongoose jestjs


    【解决方案1】:

    天真的方法是模拟方法find,它会使用方法exec返回对象(有关详细信息,请查看ways to mock modules 上的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
    });
    
    

    但在我看来,模拟每个内部方法需要大量手动工作。

    相反,我建议你更深一层地嘲笑。用mockingoose 模拟mongoose 模型。

    从未与mongoose 合作过,因此无法提供此方法的示例。

    【讨论】:

    • 我试过这样jest.mock("../mongo/models"); Vessels.find.mockReturnThis();,在测试中我使用Vessels.exec.mockResolvedValueOnce([mockVesselResponse]);。但它仍然不起作用,错误是:TypeError: Cannot read property 'mockResolvedValueOnce' of undefined。我试图了解有关此的 Jest 文档,但这很棘手,并且与我的问题不太相关。
    • 我刚试过 mockingoose,幸运的是它有效:) mockingoose(Vessels).toReturn([mockVesselResponse, mockVesselResponse2], 'find');
    • 哦,应该是Vessels.prototype.find.mockReturnThis
    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2021-02-07
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多