I am trying to unit test a Node.js+Express REST API. It's all very standard CRUD stuff and the backend database library is MongoDB being called with Mongoose. So far, so standard...
I want to use SuperTest to test my API controllers/routes, so naturally I need to stub out the database calls
This is where I'm struggling, especially with chained calls such as .limit() and .skip() on my query results.
Trying to stub the mongoose DocumentQuery limit function with sinon doesn't work, e.g.
const stubQuery = sinon.stub(mongoose.DocumentQuery, 'limit')
.callsFake(()=>{})
Results in an error
Trying to stub property 'limit' of undefined
I've tried using the sinon-mongoose library but I can't get that to work in the context of my API calls in SuperTest. It seems to only be for running tests on the models directly which I'm not doing
My test looks like this
const app = require('../server').app;
// stub out model.find()
const stubModelFind = sinon.stub(mongoose.Model, 'find').callsFake(() => {
return [ { foo: "bar" /* fake documents */ } ]
})
describe('Thing API', () => {
it('returns some things', (done) => {
request(app)
.get('/api/things')
.expect(function(res) {
expect(res.body).to.be.an.an('array')
// Rest of my tests / validation checks here
})
.expect(200, done);
});
})
This test fails with this.model.find(...).limit is not a function as my service (which is the layer in my code that talks to the DB via Mongoose) looks a little like this (where this.model is an instance of a Mongoose model)
let items = await this.model.find(query)
.limit(limit)
.skip(skip);