edu*_*ike 3 javascript mocha.js node.js promise chai
我对 mocha.js 还很陌生,所以尝试用一个最小的例子来获得一些相当基本和可靠的东西。
我正在尝试对示例 JSON API 执行 GET 请求并对其运行 3 个测试,所有测试都应该有不同的结果,但所有测试都得到与预期不同的结果。
此外,我试图捕获并计算/报告测试中发生的错误,以输出after()所有测试运行的详细信息,以免弄乱 UI。
对于 3 项测试,我只有 1 项应该通过。问题是,如果我包含一个.finally()调用,那么所有调用都会通过,如果我删除该.finally()调用并且只有该.catch()调用,那么所有调用都会失败。不知道我错过了什么。
let errors = []
// After All output error details
after((done) => {
console.log("Total Errors: " + errors.length)
// console.log(errors)
done()
})
// Example Test Suite
describe("Example Test Suite", () => {
it("#1 Should Pass on expect 200", (done) => {
request("https://jsonplaceholder.typicode.com/")
.get("todos/1")
.expect(200)
.catch(function (err) {
errors.push(err)
done(err)
})
.finally(done())
})
it("#2 Should Fail on wrong content type", (done) => {
request("https://jsonplaceholder.typicode.com/")
.get("todos/1")
.expect("Content-Type", "FAIL")
.catch(function (err) {
errors.push(err)
done(err)
})
.finally(done())
})
it("#3 Should Fail on contain.string()", (done) => {
request("https://jsonplaceholder.typicode.com/")
.get("todos/1")
.then(function (err, res) {
if (err) {done(err)} else {
try {
expect(res.text).to.contain.string("ThisShouldFail");
} catch(e) {
errors.push({error: e, response: res})
done(err)
}
finally {
done()
}
}
}).catch(function (err) {
errors.push(err)
done(err)
})
.finally(done())
})
})
Run Code Online (Sandbox Code Playgroud)
我发现所提供的测试存在两个问题
.finally(done())立即成功完成测试,因为.finally等待回调并done就地调用,.finally(done)或者.finally(() => done())可能按您的预期工作。
通过 try/catch 拦截错误是一种非常糟糕的做法,您的实现将吞掉潜在的错误,同时将测试标记为通过,即使它失败了,最好使用 mocha 的测试上下文,因为这是一个 afterEach 钩子,对于例子:
const errors = [];
afterEach(function () {
if (this.currentTest.state === "failed") {
errors.push(this.currentTest.title)
}
});
Run Code Online (Sandbox Code Playgroud)
在摩卡中使用 Promise 时也不需要调用 Done。可以简单地返回一个承诺,并且当承诺解决时,摩卡将通过测试,否则将失败(如果错误未被捕获)。
it("...", () => {
return request(...).get(...).then(...)
}
Run Code Online (Sandbox Code Playgroud)
或使用 async/await,它隐式返回一个承诺
it("...", async () => {
const result = await request(...).get(...)
// Do assertions on result
...
// No need to return anything here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |