Mocha + supertest + assert:测试失败时打印响应体

9

我正在使用 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,但仅当测试失败时?如果可能的话,我希望不必在每个"describe"块中都放置类似于console.log(res.body) if test.failed的东西。

2个回答

4

我也是这样做的:

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也被漂亮而且色彩鲜艳地显示出来。可能有更适当的处理方式,但这是一种不错的懒惰方法。


2

有多种方法可以实现这个目标:

选项1: 我会简单地使用if条件来检查else块中的失败条件,并打印console.log(res.body)

选项2: 或者在回调函数中,如果有错误,则可以返回res.body。

例如:

最后可以使用以下类似的内容

.end(function(err, res){
        if (err) throw err;
        if (!res.body.password) assert.fail(res.body.password, "valid password", "Invalid password") 
        else done()
    }); 

你可以使用res.body代替res.body.password。
尝试一下,应该可以工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接