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('asser...

问题:

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)


回答1:

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.


回答2:

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
});
  • 发表于 2019-01-11 14:47
  • 阅读 ( 236 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除