1

Hi I am new to testing with Mocha let alone async testing. I keep getting the following error when running this test. I have spend a lot of time researching the resolution on the web but no luck.

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

it('Should fail to create new user due to missing email', (done) => {
  const user_empty_email = {
    name: "First Name",
    email: "",
    password: "password",
    isAdmin: false
  }
  chai.request(app).post('/v1/users')
    .send(user_empty_email)
    .then((res) => {
      expect(res).to.have.status(400);
      done();
    }).catch(done)
})

Below is an example response I am getting fir the /v1/users

{
  "user": {
      "_id": "5de4293d3501dc21d2c5293c",
      "name": "Test Person",
      "email": "testemail@gmail.com",
      "password": "$2a$08$8us1C.thHWsvFw3IRX6o.usskMasZVAyrmccTNBjxpNQ8wrhlBt6q",
      "isAdmin": false,
      "tokens": [
          {
              "_id": "5de4293d3501dc21d2c5293d",
              "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGU0MjkzZDM1MDFkYzIxZDJjNTI5M2MiLCJpYXQiOjE1NzUyMzM4NTN9.mi4YyYcHCvdYrl7OuI5eDwJ8xQyKWDcqgKsXRYtn0kw"
          }
      ],
      "__v": 1
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGU0MjkzZDM1MDFkYzIxZDJjNTI5M2MiLCJpYXQiOjE1NzUyMzM4NTN9.mi4YyYcHCvdYrl7OuI5eDwJ8xQyKWDcqgKsXRYtn0kw"
}
rf guy
  • 379
  • 10
  • 26
  • Side note: You can simply return the Promise returned by `chai.request` instead of using `done`. Makes test far cleaner. See: https://stackoverflow.com/questions/26571328/how-do-i-properly-test-promises-with-mocha-and-chai – nicholaswmin Dec 02 '19 at 15:40

4 Answers4

2

why don't you try increasing the timeout in (ms), it's normal for tests to run slow especially when your testing network requests.

package.json

"test": "mocha --timeout 10000"

Dan Starns
  • 3,765
  • 1
  • 10
  • 28
  • Yes, I was able to resolve it by remove a test for the mongoDB connection. I think was closing the connection causing other test to fail. – rf guy Dec 06 '19 at 23:59
  • @rfguy cool, maybe you could update your question or answer it yourself? it's left unanswered and makes StackOverflow messy (filled with unanswered questions) – Dan Starns Dec 07 '19 at 01:21
2

Is there a chance that your endpoint actually takes more than 2 seconds to run? If so, you might want to increase the timeout when running Mocha: Change default timeout for mocha.

Also, does your endpoint return a response? If not, increasing the timeout will not help. Could you add the code of the /v1/users endpoint to your question to look into that possibility?

Yves Gurcan
  • 1,096
  • 1
  • 10
  • 25
1

Not sure about this. But as far as i recall mixing Promises and callback-style (done-callback) can cause such problems in mocha.

Try using Promises only:

  • remove all done from test
  • actually return the Promise (return chai.request...)
alexloehr
  • 1,773
  • 1
  • 20
  • 18
0

the issue was this test: mongoDB-connect.js

It was ran before the others. mongoDB connection was being closed which caused the other tests to timeout. When I removed the close command all tests passed as expected.

"use strict";
// NPM install mongoose and chai. Make sure mocha is globally
// installed
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const chai = require('chai');
const expect = chai.expect;
// Create a new schema that accepts a 'name' object.
// 'name' is a required field
const testSchema = new Schema({
  name: { type: String, required: true }
});

// mongoose connect options
var options = {
    useNewUrlParser: true,
    useUnifiedTopology: true
}

//Create a new collection called 'Name'
const Name = mongoose.model('Name', testSchema);
describe('Database Tests', function() {
  //Before starting the test, create a sandboxed database connection
  //Once a connection is established invoke done()
  before(function (done) {    
    // mongoose.connect('mongodb://localhost:27017',options);
    mongoose.connect('mongodb://ip/testDatabase',options);
    const db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error'));
    db.once('open', function() {
      console.log('We are connected to test database!');
      done();
    });
  });
  describe('Test Database', function() {
    //Save object with 'name' value of 'Mike"
    it('New name saved to test database', function(done) {
      var testName = Name({
        name: 'Mike'
      });

      testName.save(done);
    });
    it('Dont save incorrect format to database', function(done) {
      //Attempt to save with wrong info. An error should trigger
      var wrongSave = Name({
        notName: 'Not Mike'
      });
      wrongSave.save(err => {
        if(err) { return done(); }
        throw new Error('Should generate error!');
      });
    });
    it('Should retrieve data from test database', function(done) {
      //Look up the 'Mike' object previously saved.
      Name.find({name: 'Mike'}, (err, name) => {
        if(err) {throw err;}
        if(name.length === 0) {throw new Error('No data!');}
        done();
      });
    });
  });
  //After all tests are finished drop database and close connection
  after(function(done){
    mongoose.connection.db.dropDatabase(function(){
      mongoose.connection.close(done);
    });
  });
});
rf guy
  • 379
  • 10
  • 26