I want to run tests on the API routes of my Express App. I use Mongoose and it's Schemas for DB operations. This is my Setup of the test (it runs successfully first, but then fails when it reloads...):
const request = require('supertest');
// this loads the whole express app
const app = require('../../server');
describe('[Auth]', function () {
it('returns 401 with invalid credentials', function (done) {
request(app)
.post('/auth/login')
.field('email', 'invalidMail')
.field('password', 'invalidPassword')
.expect('Content-Type', contentType)
.expect(401, done);
}
}
This test is successfull when I start mocha. I start it in --watch mode
and whenever I save a file and mocha restarts the test i get the following error:
MongooseError: Cannot overwrite `user` model once compiled.
at Mongoose.model (...\node_modules\mongoose\lib\index.js:376:13)
...
What I tried is connecting and disconnecting Mongoose in the before
and after
hooks but that didn't change anything.
Seems to me that Mocha is just reloading my app without stopping it first. What am I missing here? What's the best practice?