简体   繁体   中英

Why do I keep facing a Mocha "timeout error"; Also node keeps telling me to resolve my promise?

I keep getting a timeout error, it keeps telling me to enusre I have called done(), even though I have.

  const mocha = require('mocha');

  const assert = require('assert');

  const Student = require('../models/student.js');

  describe('CRUD Tests',function(){
     it('Create Record',function(done){
         var s = new Student({
            name: "Yash"
         });

         s.save().then(function(){
            assert(s.isNew === false);

            done();
         });
     });
 });

Result is -

CRUD Tests 1) Create Record

0 passing (2s) 1 failing

1) CRUD Tests Create Record: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/yash/Documents/Development/Node/MongoCRUD/test/CRUD_test.js)

I guess that your mocha runs without being connected to your database. So .save() is waiting for a connection which it never get and your mocha timeout.


You can initialize your software system before to run any Mocha test.

For example, connect a database.

// ROOT HOOK Executed before the test run
before(async () => {
    // connect to the database here
});

// ROOT HOOK Excuted after every tests finished
after(async () => {
    // Disconnect from the database here
});

Note that as written, your unit test ignores the fact that save() might reject instead of resolving. Whenever you use this done construct, make sure your unit test handles an error scenario, like this:

     s.save().then(function() {
        assert(s.isNew === false);

        done();
     }).catch(error => {
        done(error);
     });

Alternatively, since Mocha has built-in support for promises, you can remove the done parameter and return the promise directly, like this:

it('Create Record', function() {
    // ...

    return s.save().then(function() {
        assert(s.isNew === false);
     });
});

The advantage with this approach is a reject promise will automatically fail the test, and you don't need any done() calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM