Mocha: Error Timeout of 2000ms exceeded

34,075

Solution 1

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)

Solution 2

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

Solution 3

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

Share:
34,075
user1107173
Author by

user1107173

Updated on July 09, 2022

Comments

  • user1107173
    user1107173 almost 2 years

    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?

  • Mulan
    Mulan over 7 years
    Yeah but adjusting the timeout in this case isn't going to help.
  • Gene Bo
    Gene Bo over 4 years
    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