承诺拒绝因 chai-as-promised 而失败
Promise rejection failed with chai-as-promised
我使用 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;
});
此测试失败并显示错误:测试(我使用 Intern 作为单元测试库)虽然下面的测试通过了:
bdd.it("Test rejection", function () {
var promise = q.promise(function (resolve, reject, notify) {
reject(new Error("test"));
}).should.be.rejectedWith(Error);
return promise;
});
库需要您 return .rejectedWith()
的 return 值,以便它测试断言。您只是在测试过程中调用 .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);
});
我使用 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;
});
此测试失败并显示错误:测试(我使用 Intern 作为单元测试库)虽然下面的测试通过了:
bdd.it("Test rejection", function () {
var promise = q.promise(function (resolve, reject, notify) {
reject(new Error("test"));
}).should.be.rejectedWith(Error);
return promise;
});
库需要您 return .rejectedWith()
的 return 值,以便它测试断言。您只是在测试过程中调用 .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);
});