javascript - 为什么我一直面对摩卡 "timeout error"; Node 还一直告诉我兑现我的 promise ?

标签 javascript node.js mongodb

我不断收到超时错误,它不断告诉我是否已调用done(),即使我已经调用了。

  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();
         });
     });
 });

结果是 -

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)

最佳答案

请注意,正如所写,您的单元测试忽略了 save() 可能拒绝而不是解析的事实。每当您使用此 done 构造时,请确保您的单元测试能够处理错误场景,如下所示:

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

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

或者,由于 Mocha 内置了对 Promise 的支持,您可以删除 done 参数并直接返回 Promise,如下所示:

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

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

这种方法的优点是拒绝 promise 将自动使测试失败,并且您不需要任何 done() 调用。

关于javascript - 为什么我一直面对摩卡 "timeout error"; Node 还一直告诉我兑现我的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54125817/

相关文章:

java - 将天数转换为周数的数学公式是什么

javascript - 防止双击添加到购物车按钮

Node.js Rest api 验证来自 url 的传入 json

Java Android 应用程序和 Node.js + Express.js API

javascript - Materializecss 的复选框输入不适用于 jQuery

javascript - Google map (ngmap 指令)- 未捕获的 TypeError : Cannot read property 'x' of undefined

node.js - Nestjs - 在普通 Controller 中连接牛板

node.js - 在 Node.JS Web 应用程序中使用 mongoDB

mongodb - Golang 数据库连接池与 mongodb

java - 无法连接到 Bluemix 中的 mongodb,找不到证书路径