2
votes

I'm trying to stub the find or exec functions to test the following function:

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();
}

I found several posts about stubbing mongoose methods but none of them worked for me, here is what I have:

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

But I get:

Cannot read property 'populate' of undefined

so I tried replacing it with a fake object:

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);
    }
}

And

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

And the result is:

TypeError: this.fakeFn.apply is not a function

I've also tried stubbing mongoose.Model, prototype, exec, and some other stuff with no luck.

Any ideas?

1

1 Answers

1
votes

Try to use sinon-mongoose https://github.com/underscopeio/sinon-mongoose

Here is an example:

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');