在 Mocha 中,返回将被拒绝的承诺与调用 done(err) 的效果不同

In Mocha, returning a promise that will be rejected doesn't have the same effect as calling done(err)

本文关键字:err done 调用 承诺 Mocha 返回 拒绝      更新时间:2023-09-26

摩卡文档状态

或者,您可以返回一个 承诺。如果您正在测试的 API 返回承诺,这将非常有用 而不是接受回调

但在拒绝时,这两种方式似乎有不同的结果:

var Promise = require("bluebird");
describe('failure', function () {
    describe('why2describes', function () {
        it("fails caught", function (done) {
            new Promise(function (resolve, reject) {
                reject(new Error("boom"))
            }).catch(function (err) {
                done(err)
            })
        });
        it("fails return", function (done) {
            return new Promise(function (resolve, reject) {
                reject(new Error("boom"))
            })
        });
    })
});

第一个结果是

Error: boom

第二个结果是

Unhandled rejection Error: boom

然后另外声明Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

我在第二种情况下做错了什么吗?

我在第二种情况下做错了什么吗?

是的。两件事。

  1. 当您没有将catch处理程序附加到 Promise 链时,错误发生在链中,将以拒绝 promise 的形式丢失。蓝鸟通过检测并抛出该错误来确保不会发生类似的事情

    Unhandled rejection Error: boom
    
  2. 在异步情况下,调用 done 函数是让测试处理器知道当前测试已完成的方法。在第二种情况下,您从不调用done。因此,它等待默认超时 2000 毫秒,然后测试用例失败并出现该错误。

    但是,如果你喜欢使用承诺/你的API返回一个承诺,那么你根本不应该使用done函数。您的代码应如下所示

    it("fails return", function () { // no `done` argument here
        return new Promise(function (resolve, reject) {
            // ideally you would be doing all the assertions here
        })
    });
    

    处理基于 Promise 的测试时要注意的另一件重要事情是,您应该返回 promise 对象。