gpt4 book ai didi

node.js - Stub Mongoose 查找方法

转载 作者:太空宇宙 更新时间:2023-11-03 22:09:08 26 4
gpt4 key购买 nike

我正在尝试 stub find 或 exec 函数来测试以下函数:

function getOpenTickets() {
return Ticket.find({})
.populate('assignees', ['fullName', 'firstName', 'email', 'notificationSettings.dailyEmail'])
.populate('property', 'name')
.populate('type', 'title')
.populate({path: 'unit', model: 'Unit', select: 'title'})
.sort('created')
.lean()
.exec();
}

我发现了几篇关于 stub Mongoose 方法的帖子,但没有一个对我有用,这是我所拥有的:

it('should test getOpenTickets', async() => {
findStub = sinon.stub(Ticket, 'find');
var result = await utils.__get__('getOpenTickets')();
findStub.restore();
});

但我得到:

Cannot read property 'populate' of undefined

所以我尝试用假对象替换它:

var fakeFind = {
args: {
populate: [],
sort: null,
lean: null
},
populate: function (a) {
this.args.populate.push(a)
},
sort: function (a) {
this.args.sort = a;
},
lean: function () {
this.args.lean = true
},
exec: function () {
return Promise.resolve(this.args);
}
}

还有

findStub = sinon.stub(Ticket, 'find').callsFake(fakeFind);

结果是:

TypeError: this.fakeFn.apply is not a function

我也尝试过对 mongoose.Model、prototype、exec 和其他一些东西进行 stub ,但没有成功。

有什么想法吗?

最佳答案

尝试使用 sinon-mongoose https://github.com/underscopeio/sinon-mongoose

这是一个例子:

require('sinon');
require('sinon-mongoose');

sinon.mock(Ticket)
.expects('find')
.chain('populate').withArgs(/* args */)
.chain('sort').withArgs('create')
.chain('lean')
.chain('exec')
.resolves('SOME_VALUE');

关于node.js - Stub Mongoose 查找方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com