17

I am trying to seed the database for unit test.

Below is the seed.js file:

.......
const app = require('./app')
const db = app.get('db')

const saveUsersToDB = (done) => {
    db.User.bulkCreate(users)
         .then(() => (done))
}

module.exports = {saveUsersToDB};

My app.test.js file:

.......
const expect = require('expect')
const request = require('supertest')
const {saveUsersToDB} = require('./seed/seed');

before(saveUsersToDB)

When I run the test below is the error I get:

Express listening on port 3000!
  1) "before all" hook: saveUsersToDB

  0 passing (2s)
  1 failing

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

npm ERR! Test failed.  See above for more details.

I thought returning .then(() => (done)) was enough? What am I doing wrong?

user1107173
  • 10,334
  • 16
  • 72
  • 117

3 Answers3

24

By default, Mocha tests have a 2 second timeout (which means that the test needs to be completed in 2 seconds).

You can increase it (in milliseconds) as follows:

this.timeout(5000); // this test can take up to 5 seconds

https://mochajs.org/#timeouts

Pang
  • 9,564
  • 146
  • 81
  • 122
Kalman
  • 8,001
  • 1
  • 27
  • 45
  • 2
    Yeah but adjusting the timeout in this case isn't going to help. – Mulan Dec 02 '16 at 12:27
  • Was looking at a bunch of answers on SO regarding this error - none of them working for me until I found this one. Nice, Thank you – Gene Bo Feb 11 '20 at 01:00
13

Because (done) will actually return the function instead of invoking it. In order to call done, you need to write it this way.

.then(() => done())

However, I don't recommend using done along with promises. You just simply need to return the promise then mocha will handle it automatically.

const saveUsersToDB = () => db.User.bulkCreate(users)
Lewis
  • 14,132
  • 12
  • 66
  • 87
9

I had the same isue. This error promps because the 2 seconds timeout, so if your test needs to connect to ddbb it will most provably surpas it.

What I did was to separate all my tests that needed somme kind of connection to external resources into my integration tests folder and then added the next flag in my package.json test script:

"int-test": "mocha --timeout 15000 tests/integration/**/*.test.js --compilers js:babel-register "

Follow this link for other ways to increase the timeout: mocha timout

sendra
  • 658
  • 1
  • 9
  • 21