gpt4 book ai didi

javascript - should.js 不会导致 mocha 测试失败

转载 作者:数据小太阳 更新时间:2023-10-29 05:52:17 25 4
gpt4 key购买 nike

我对单元测试、mocha 和 should.js 非常陌生,我正在尝试为返回 promise 的异步方法编写测试。这是我的测试代码:

var should = require("should"),
tideRetriever = require("../tide-retriever"),
moment = require("moment"),
timeFormat = "YYYY-MM-DD-HH:mm:ss",
from = moment("2013-03-06T00:00:00", timeFormat),
to = moment("2013-03-12T23:59:00", timeFormat),
expectedCount = 300;

describe("tide retriever", function() {
it("should retrieve and parse tide CSV data", function() {
tideRetriever.get(from, to).then(
function(entries) { // resolve
entries.should.be.instanceof(Array).and.have.lengthOf(expectedCount);
},
function(err) { // reject
should.fail("Promise rejected", err);
}
);
});
});

当我手动测试 tideRetriever.get方法,它始终如一地解析 27 个元素的数组(如预期的那样),但无论 expectedCount 的值如何,测试都不会失败。 .这是我的简单手动测试:

tideRetriever.get(from, to).then(
function(entries) {
console.log(entries, entries.length);
},
function(err) {
console.log("Promise rejected", err);
}
);

如果有必要,我也可以发布被测模块的源代码。

我是不是对 Mocha 或 should.js 有什么误解?任何帮助将不胜感激。

最佳答案

更新

在某些时候,Mocha 开始支持从测试返回 Promise 而不是添加 done() 回调。原始答案仍然有效,但使用这种方法测试看起来更清晰:

it("should retrieve and parse tide CSV data", function() {
return tideRetriever.get(from, to).then(
function(entries) {
entries.should.be.instanceof(Array).and.have.lengthOf(expectedCount);
}
);
});

查看 this gist完整的例子。

原创

注意。接受的答案仅适用于普通的异步代码,不适用于 Promises(作者使用的)。

不同之处在于应用程序(在我们的例子中是 Mocha)无法捕获 Promise 回调抛出的异常,因此测试将因超时而不是实际断言而失败。根据 Promise 的实现,可以记录或不记录断言。在 when documentation 查看更多相关信息.

要使用 Promises 正确处理此问题,您应该将 err 对象传递给 done() 回调,而不是抛出它。您可以使用 Promise.catch() 方法(不在 Promise.then()onRejection() 回调中),因为它不会't catch exceptions from onFulfilment() callback of the same method)。请参见下面的示例:

describe("tide retriever", function() {
it("should retrieve and parse tide CSV data", function(done) {
tideRetriever.get(from, to).then(
function(entries) { // resolve
entries.should.be.instanceof(Array).and.have.lengthOf(expectedCount);
done(); // test passes
},
function(err) { // reject
done(err); // Promise rejected
}
).catch(function (err) {
done(err); // should throwed assertion
});
});
});

PS done() 回调在三个地方使用,以涵盖所有可能的情况。但是,如果您不需要其中的任何特殊逻辑,则可以完全删除 onRejection() 回调。 Promise.catch() 也会在这种情况下处理拒绝。

关于javascript - should.js 不会导致 mocha 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24071493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com