I am trying to write a unit test that should perform an integration test between a REST endpoint and the controller belonging to it. The test should mock the call to the database so no database connection is established during testing.
I am using chai-http to make the HTTP call to the endpoint and sinon with sinon-mongoose to mock the Mongoose models calls.
const set = [{ _id: 1 }, { _id: 2 }, { _id: 3 }];
//Require the dev-dependencies
const sinon = require('sinon');
const { describe, it } = require('mocha');
require('sinon-mongoose');
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../src/server');
const should = chai.should();
// set up mocks
const MyModel = require('../src/models/myModel');
const MyModelMock = sinon.mock(MyModel);
MyModelMock.expects('find').yields(set);
chai.use(chaiHttp);
describe('My endpoints', () => {
describe('/GET to my endpoint', () => {
it('it should GET all the info I want', (done) => {
chai.request(server)
.get('/api/myEndpoint')
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});
});
Googling this error did not yield any results that I am able to work with. What am I doing wrong here?
I am trying to write a unit test that should perform an integration test between a REST endpoint and the controller belonging to it. The test should mock the call to the database so no database connection is established during testing.
I am using chai-http to make the HTTP call to the endpoint and sinon with sinon-mongoose to mock the Mongoose models calls.
const set = [{ _id: 1 }, { _id: 2 }, { _id: 3 }];
//Require the dev-dependencies
const sinon = require('sinon');
const { describe, it } = require('mocha');
require('sinon-mongoose');
const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../src/server');
const should = chai.should();
// set up mocks
const MyModel = require('../src/models/myModel');
const MyModelMock = sinon.mock(MyModel);
MyModelMock.expects('find').yields(set);
chai.use(chaiHttp);
describe('My endpoints', () => {
describe('/GET to my endpoint', () => {
it('it should GET all the info I want', (done) => {
chai.request(server)
.get('/api/myEndpoint')
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});
});
Googling this error did not yield any results that I am able to work with. What am I doing wrong here?
Share Improve this question asked Nov 8, 2019 at 11:09 SecretIndividualSecretIndividual 2,5694 gold badges26 silver badges61 bronze badges1 Answer
Reset to default 7In case someone ever runs into this (most likely future me).
I managed to solve my issue. I was using promises in my code and should have set up my mock accordingly (also chaining correctly).
MyModelMock.expects('find').chain('where').chain('in').chain('exec').resolves(set);