【问题标题】:Promise rejection failed with chai-as-promised承诺拒绝失败,chai-as-promised
【发布时间】:2017-03-16 19:36:26
【问题描述】:

我使用 chai-as-promised 库和 q 库生成的 promise。 这个简单的测试用例应该可以工作(承诺必须被拒绝)还是我误解了承诺功能?

bdd.it("Test rejection", function () {
    var promise = q.promise(function (resolve, reject, notify) {
        reject(new Error("test"));
    }).then(function () {
        // Nothing to do
    });
    promise.should.be.rejectedWith(Error);
    return promise;
});

这个测试失败并出现错误:测试(我使用实习生作为单元测试库)虽然下面的测试通过了:

bdd.it("Test rejection", function () {
    var promise = q.promise(function (resolve, reject, notify) {
        reject(new Error("test"));
    }).should.be.rejectedWith(Error);
    return promise;
});

【问题讨论】:

    标签: promise q chai-as-promised


    【解决方案1】:

    该库需要您返回 .rejectedWith() 的返回值,以便它测试断言。您只是在测试过程中调用.should.be.rejectedWith(),它对此无能为力。

    如果您查看documentation for chai-as-promised,您会发现这正是他们在示例中所做的:

    return promise.should.be.rejectedWith(Error); 
    

    对于其他基于 Promise 的断言也是如此,例如 .should.become()

    你的第二个测试是正确的。您也可以只使用return,而不是先将结果分配给变量:

    bdd.it("Test rejection", function () {
        return q.promise(function (resolve, reject, notify) {
            reject(new Error("test"));
        }).should.be.rejectedWith(Error);
    });
    

    【讨论】:

    • 好的,但是如何检查几个条件,例如拒绝和错误代码等于 31 的示例?
    • @Troopers 我不确定,但我认为你可以这样做 return q.promise(.....).catch(function (error) { /* perform ordinary assertions on error */ });
    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多