5

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?

Chris
  • 2,069
  • 3
  • 22
  • 27
  • I want to know this too. I can ctrl-c and restart and all tests pass.. but if I save a file it throws this error. – Michael Bruce Mar 18 '17 at 21:02
  • 1
    Thas was a while ago and I actually didn' find an answer. I solved it tho, by not using Mocha anymore. It worked great with Tape (https://github.com/substack/tape) and also with Jest (https://facebook.github.io/jest/) – Chris Jun 21 '17 at 12:22
  • I've seen a similar behaviour with Hydra and TypeORM, it just reloads without stoping them. – Emir Herrera Mar 03 '20 at 06:27

0 Answers0