我正在使用 mocha、supertest 和 assert 来测试我的 Express 应用程序。我的 Express 应用程序在开发模式下运行,因此只要请求失败,它就会以 JSON 形式返回有用的调试信息。我想在我的测试套件中打印此数据,但仅在测试失败时打印。我的一个测试示例(在 CoffeeScript 中):
assert = require "assert"
request = require "supertest"
url = request "http://localhost:3000"
describe "GET /user/:id", ->
it "should return one user", (done) ->
url
.get("/user" + id)
.expect(200)
.expect("Content-Type", /json/)
.end (err, res) ->
if err
done err
else
# assuming the test reaches here, but fails on one of the following,
# how do i make mocha print res.body?
assert.equal(res.body.name, user.name)
assert.equal(res.body.email, user.email)
done()
我如何使 mocha 打印 res.body,但仅当测试失败时?我宁愿不必放置类似
console.log(res.body) if test.failed
的内容在每个 describe
如果可能,阻止。
最佳答案
我也是这样做的:
var supertest = require("supertest");
var should = require("should");
var util = require('util');
describe("My test",function(){
var response;
it("should validate the API key",function(done){
server
.post("/validate")
.set('authorization', apiKey)
.expect("Content-type",/json/)
.expect(200)
.end(function(err,res){
response = res;
res.status.should.equal(200);
res.body.error.should.equal(false);
done();
});
});
afterEach(function(){
if (this.currentTest.state == 'failed') {
console.log(" Response body: " + util.inspect(response.body,{depth: null, colors: true}) + "\n");
}
})
});
我献上了
response
我的测试范围中的变量,每个测试将其设置为给定的响应( response = res;
)。我必须在每次测试中做一次,但是我不必担心它何时何地失败。之前,我不得不小心,因为如果测试失败,它下面的一些代码将不会被执行,因此它甚至不会到达打印语句。这样,无论结果如何,我都可以保存我需要的东西。然后每次测试后,这个
afterEach
事件将开始并检查测试是通过还是失败。 afterEach(function(){
if (this.currentTest.state == 'failed') {
console.log(" Response body: " + util.inspect(response.body,{depth: null, colors: true}) + "\n");
}
})
这为每个测试提供了一致的打印方式。所有测试只有1行,所以很容易改变格式或禁用,我不需要关心测试失败的地方,我只关心最终的结果。在我看来,这是所有懒惰方法中最好和最简单的方法。甚至输出的 JSON 也能很好地、丰富多彩地显示出来。可能有更合适的方法来处理它,但这是一种不错的懒惰方法。
关于express - Mocha + super 测试 + 断言 : print response body on test failure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25347386/