Stub Mongoose查找方法

时间:2017-12-07 21:42:38

标签: node.js unit-testing mocha sinon

我试图将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();
}

我发现了一些关于存在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和其他一些没有运气的东西。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试使用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');