【问题标题】:handle different responses using mocha in nodejs unit testing在 nodejs 单元测试中使用 mocha 处理不同的响应
【发布时间】:2018-06-28 13:48:45
【问题描述】:

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

这是我的代码,(这里我传递了错误的标题信息,所以响应将是状态 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)

【问题讨论】:

    标签: javascript node.js unit-testing testing mocha.js


    【解决方案1】:

    正如另一个答案中提到的,您不能同时测试 200 和 400。

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

    chai-httpsupports promise control flow。 Mocha 自然会处理 Promise,测试应该返回 Promise 而不是使用done。因为它是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);
        });
      });
    });
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢你的回复,你能不能帮我看看,如何同时测试200和400代码,我没有任何参考代码,请帮助我
      • 您应该有两个 its 一个具有正确的标头,用于测试 200,另一个具有错误的标头,用于测试 400。您不能在同一个 it 中同时测试两者
      猜你喜欢
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2021-09-14
      • 1970-01-01
      相关资源
      最近更新 更多