首页 文章

Mocha supertest断言:测试失败时打印响应体

提问于
浏览
5

我正在使用mocha,supertest和assert来测试我的Express应用程序 . My 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 print res.body,但仅在测试失败时?如果可能的话,我宁愿不必在每个 describe 块中放置像 console.log(res.body) if test.failed 这样的东西 .

2 回答

  • 1

    我这样做:

    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; ) . 我必须在每次测试中做一次,但之后我不会被执行,所以它甚至都不会达到print语句 . 这样,无论结果如何,我都会保存我需要的东西 .

    然后在每次测试之后,这个 afterEach 事件将启动并检查测试是否通过或失败 .

    afterEach(function(){
        if (this.currentTest.state == 'failed') { 
          console.log("    Response body: " + util.inspect(response.body,{depth: null, colors: true}) + "\n");
        }
      })
    

    这为每个测试提供了一致的打印方式 . 所有测试只有一行,所以很容易改变格式或禁用,我不需要关心测试失败的地方,我只关心最终的结果 . 在我看来,这似乎是所有懒惰方法中最好和最简单的方法 . 即使是输出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

    试试这个它应该工作 .

相关问题