要记录有关摩卡测试错误的响应正文吗?

时间:2019-01-12 03:22:20

标签: node.js npm mocha response chai

使用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很好。

1 个答案:

答案 0 :(得分:0)

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

之所以不理想,是因为每个测试都需要一行,这会用该测试的响应来更新共享变量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();
      });
  });

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

相关问题