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

Javascript 在nodejs单元测试中使用mocha处理不同的响应,javascript,node.js,unit-testing,testing,mocha.js,Javascript,Node.js,Unit Testing,Testing,Mocha.js,当我通过正确的标题信息时,我的测试通过了(200状态代码)。但是当我尝试使用错误的信息(400状态码)时,它无法处理该错误 这是我的代码,(这里我传递了错误的头信息,所以响应将是状态400代码) 我犯了这样的错误 GET USER (node:28390) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected undefined to eq

当我通过正确的
标题
信息时,我的测试通过了
200状态代码
)。但是当我尝试使用错误的信息(
400状态码)时,它无法处理该错误

这是我的代码,(这里我传递了错误的头信息,所以响应将是状态400代码)

我犯了这样的错误

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)

这里似乎有一个小小的误解:如果http
chai
接收到http错误,则不会执行
catch
。如果请求失败,则执行该命令。获取
200
400
都应该在
中测试,然后在
中测试,而不是捕获


从错误消息中可以看到,
err
对象没有
status
字段,因为它不是
response
对象,而是
error
的实例,如另一个答案中所述,您不能同时测试200和400

如果断言失败,则在
expect
之前调用
done()
将导致测试超时,因为它会抛出断言错误,并且从不调用
done
。这将导致未处理的拒绝,因为在
catch
之后没有另一个
catch

http
。摩卡自然会处理承诺,测试应该返回承诺,而不是使用
done
。实际上,错误响应可以通过
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);
    });
  });
});

谢谢你的回复,你能告诉我,如何在同一时间测试200和400个代码吗?我没有任何参考代码,请帮助我。你应该有两个
it
s,一个标题正确,你测试
200
,另一个标题错误,你测试
400
。不能在同一个
it
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);
    });
  });
});