在nodejs单元测试中使用mocha处理不同的响应

handle different responses using mocha in nodejs unit testing

当我传递正确的 header 信息时,我的测试得到 passed(200 status code)。但是当我尝试使用 wrong info(400 status code) 时,它无法处理该错误,

这是我的代码,(这里我传递了错误的 headers 信息,因此响应将是状态 400 代码)

const chai = require('chai');
const expect = require('chai').expect;
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const main  = require('../server');
let token;
describe('GET USER', function()  {
  this.timeout(50000);
  it('Display info about user and returns a 200 response', (done) => {
    chai.request(main)
    .get('/users')
    .set("Authorization"," ")
    .then(function(response) {
      // Now let's check our response
      expect(response).to.have.status(200);
      done();
    })
    .catch((err)=>{
      expect(err.status).to.be.equal(400)
      done();
    })
  });
});

我遇到这样的错误,

GET USER
(node:28390) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected undefined to equal 400
    1) Display info about user and returns a 200 response

  1 failing

  1) GET USER
       Display info about user and returns a 200 response:
     Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/test/users.test.js)

这里似乎有一个小误会:如果chai-http 收到HTTP 错误,catch 不会执行。如果请求失败则执行。获取 200400 都应该在 then 中进行测试而不是捕获。

从错误消息中可以看出,err 对象没有 status 字段,因为它不是 response 对象,而是 Error 的实例.

在另一个回答中提到,你不能同时测试200和400。

如果断言失败,在 expect 之前调用 done() 将导致测试超时,因为它会抛出断言错误并且永远不会调用 done。这导致未处理的拒绝,因为在 catch.

之后没有另一个 catch

chai-httpsupports promise control flow. Mocha naturally handles promises, a test should return a promise instead of using done. As it's suggested,错误响应可以达到err.response。它可能应该是:

describe('GET USER', function()  {
  it('should returns 400 response', () => {
    return chai.request(main)
    .get('/users')
    .set("Invalid header"," ")
    .catch(function(err) {
      expect(err.response.status).to.have.status(400);
    });
  });
});