【问题标题】:How do you use distinct with mockingoose?你如何使用 distinct 和 mockingoose?
【发布时间】:2019-03-11 06:02:01
【问题描述】:

在使用 Jest 运行测试时,我使用 Mockingoose 来模拟我的猫鼬调用。我试过了,但我得到一个错误

mockingoose.Account.toReturn(
    ["593cebebebe11c1b06efff0372","593cebebebe11c1b06efff0373"],
    "distinct"
);

错误:

ObjectParameterError: Parameter "obj" to Document() must be an object, got 593cebebebe11c1b06efff0372

然后我尝试将一个文档对象数组传递给它,但它只返回文档。我如何让它只返回一个数组或字符串?

这是我正在测试的函数中的代码:

const accountIDs = await Account.find({
    userID: "test",
    lastLoginAttemptSuccessful: true
}).distinct("_id");

如果有人知道更好的方法,我愿意接受其他方式来嘲笑我的猫鼬电话。谢谢!

【问题讨论】:

    标签: node.js mongoose jestjs mockingoose


    【解决方案1】:

    你不能。

    我的错。我研究了 mockingoose 实现并意识到,它通过实现一个模拟来“支持”不同,但它实际上只返回给定的文档,就像其他操作一样。

    为此问题打开了pull request 并添加了一个测试,因此您的示例应该是有效的并且可以工作。

    【讨论】:

    • await Account.find({}).distinct("_id"); 将返回一个字符串数组。你说不会?
    • 我是说,toReturn 部分(猫鼬实际返回的内容)必须包含一个对象数组作为第一个参数。这就是你首先得到错误的原因。
    • 对我来说似乎是猫鼬的一个问题。它通过允许使用它来“支持”不同,但模拟缺乏实现并且只是返回。为此创建了一个拉取请求。
    【解决方案2】:

    我认为答案是不要使用模仿鹅。仅凭玩笑就可以轻松完成。

    您可以使用jest.spyOn()mockImplementation() 模拟第一个调用,例如find()update()。这是findOneAndUpdate() 的示例,我们正在检查以确保传递了正确的对象:

    // TESTING:
    // await Timeline.findOneAndUpdate(query, obj);
    //
    
    const Timeline = require("./models/user.timeline");
    ...
    const TimelineFindOneAndUpdateMock = jest.spyOn(Timeline, "findOneAndUpdate");
    const TimelineFindOneAndUpdate = jest.fn((query, obj) => {
        expect(obj.sendDateHasPassed).toBeFalsy();
        expect(moment(obj.sendDate).format()).toBe(moment("2018-11-05T23:00:00.000Z").format());
    });
    TimelineFindOneAndUpdateMock.mockImplementation(TimelineFindOneAndUpdate);
    

    如果你想模拟一个链式函数,你可以让它返回一个带有你想调用的下一个链式函数的对象。下面是一个如何模拟链式distinct() 调用的示例。

    // TESTING:
    // let accountIDs = await Account.find(query).distinct("_id");
    //
    // WILL RETURN:
    // ["124512341234","124512341234","124512341234"]
    //
    
    const Account = require("./models/user.account");
    ...
    const AccountFindMock = jest.spyOn(Account, "find");
    const AccountFindDistinctResult = ["124512341234","124512341234","124512341234"];
    const AccountFindDistinctResult = jest.fn(() => AccountFindDistinctResult);
    const AccountFindResult = {
        distinct: AccountFindDistinct
    };
    const AccountFind = jest.fn(() => AccountFindResult);
    AccountFindMock.mockImplementation(AccountFind);
    

    在你的测试运行之后,如果你想检查一个函数被调用了多少次,比如distinct()被调用了多少次,你可以添加这个:

    expect(AccountFindDistinct).toHaveBeenCalledTimes(0);
    

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      相关资源
      最近更新 更多