【问题标题】:How to mock the Mongoose model for find with populate如何通过填充模拟 Mongoose 模型以进行查找
【发布时间】:2023-02-17 01:41:46
【问题描述】:

我有下面的 Node JS 和 mongoose 代码。我必须模拟此查询以在我的 JEST 单元测试中抛出错误。谁能帮我实现它?

return new Promise(async (resolve, reject) => {
        try {
            const data = await users
                .find(filter, porjectFields)
                .populate({
                    path: 'user.address',
                    populate: {
                        path: 'location'
                    }
                })
                .lean();
            resolve(data);
        } catch (err) {
            logger.error(
                `Error in user : ${err}`
            );
            reject(err);
        }
    });

我试着像下面那样模拟,但我在精益功能上遇到了错误。

users.find = jest.fn().mockImplementation(() => ({
                populate: jest.fn().mockReturnValue({ name: 'hello' }),
                lean: true
            }));

错误:

TypeError: users.find(...).populate(...).lean 不是函数

【问题讨论】:

    标签: mongoose jestjs


    【解决方案1】:

    您的想法是正确的,只是错过了精益也是一种功能。

    users.find = jest.fn().mockImplementation(() => ({
                    populate: () => ({ lean: jest.fn().mockReturnValue({ name: 'hello' }) })
                }));
    

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 1970-01-01
      • 2017-10-24
      • 2013-12-24
      • 2020-12-08
      • 2013-10-23
      • 1970-01-01
      • 2020-05-21
      • 2018-06-08
      相关资源
      最近更新 更多