2

I'm trying to setup tests for a REST API made with Express and MongoDB. I want to use mocha, chai and chai-http but I'm getting a strange behavior, it seems that the beforeEach function it's exceeding the timeout like it's never being resolved. How could i fix this?

//During the test the env variable is set to test
process.env.NODE_ENV = 'test';

let mongoose = require("mongoose");
let User = require('../models/User');

//Require the dev-dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
let app = require('../app');
let should = chai.should();

chai.use(chaiHttp);
//Our parent block
describe('Users', function () {
  beforeEach(function (done) { //Before each test we empty the database
    User.remove({}, function (err) { 
      done();         
    });     
  });
  /*
   * Test the /GET route
   */
  describe('/GET users', function () {
    it('it should GET all the users', function (done) {
      chai.request(app)
        .get('/users')
        .end(function (err, res) {
            res.should.have.status(200);
            res.body.should.be.a('array');
            res.body.length.should.be.eql(0);
          done();
        });
    });
  });

});
Julián Bonilla
  • 385
  • 1
  • 4
  • 18
  • Are you sure that you configured connection to the database properly? And connection is open when you call `User.remove`? – alexmac Apr 19 '18 at 15:33
  • What is the `remove` method? I could not find the `remove` method in [docs](http://docs.sequelizejs.com/class/lib/model.js~Model.html). So you might have implemented it. My guess is that `remove` method never calls the callback function, thus `done` is never called and hence the timeout. PS: If you are looking to delete all the entries into the db, you can use [truncate](http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-truncate) – AbhinavD Apr 20 '18 at 04:33

1 Answers1

2

Assuming your connection is working correctly and its only a timeout issue you need to extend the timeout to something beyond the default (2000ms) with the this.timeout() function. For example, adding this.timeout(10000) inside the beforeEach function would set the timeout to 10 seconds which should give your User.remove call more time to complete.

Here is an example in this SO answer: How to set timeout on before hook in mocha?

goteamtim
  • 88
  • 8