【问题标题】:Log response body on mocha test errors?记录 mocha 测试错误的响应正文?
【发布时间】:2019-01-12 03:22:19
【问题描述】:

当使用npm run test 运行 mocha 测试时,是否可以在测试失败并出现错误时打印响应正文的内容?

chai.request(server)
  .post('/')
  .set('X-Access-Token', testUser.accessToken)
  .send(fields)
  .end((error, response) => {
    console.log(response.body);       // log this!
    response.should.have.status(201); // if this fails!
    done();
  });
});

换句话说,afterEach 函数能否访问每个测试的errorresponse

afterEach(function(error, response) {
  if (error) console.log('afterEach', response.body);
});

我们在响应中有有用的错误消息,因此我们发现自己将 console.log 行粘贴到失败的测试中进行调试。总是能看到每个错误的 response.body 就好了。

【问题讨论】:

    标签: node.js npm mocha.js response chai


    【解决方案1】:

    OP 在这里 - 我想出了一个答案,我想我会把它留在这里,直到有人想出更好的答案。

    它不理想的原因是它需要在每个测试中使用一行,这会使用该测试的响应更新共享变量 currentResponse。但如果您的测试跨越多个文件,您可以在设置脚本中维护一个全局变量:

    // you can use a global variable if tests span many files
    let currentResponse = null; 
    
    afterEach(function() {
      const errorBody = currentResponse && currentResponse.body;
    
      if (this.currentTest.state === 'failed' && errorBody) {
        console.log(errorBody);
      }
    
      currentResponse = null;
    });
    

    然后您的每个测试都会更新当前响应,因此我们可以将其记录在 afterEach 中,以防失败。

    describe('POST /interests', () => {
      it('400s if categoryName field is not present in the category', done => {
        const fields = [
          { language: 'en' },
        ];
    
        chai.request(server)
          .post('/interests')
          .set('X-Access-Token', testUser.accessToken)
          .send(fields)
          .end((error, response) => {
            currentResponse = response; // update it here
            response.should.have.status(400);
            done();
          });
      });
    

    这将在出现错误时输出响应,因此您可以查看服务器返回的内容。

    【讨论】:

      猜你喜欢
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      相关资源
      最近更新 更多