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

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

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

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

最佳答案

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

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

chai-http supports 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);
    });
  });
});

关于javascript - 在nodejs单元测试中使用mocha处理不同的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51084613/

相关文章:

javascript - 正则表达式组 javascript 上的算术运算

JavaScript 依赖注入(inject)

JavaScript 数据验证器?

node.js - 从 webjob 调用 webapp 中的 API

javascript - 如何通过 ID 从 JSON 对象数组中删除数组元素

python - 跳过没有装饰器语法的单元测试测试

Javascript - 计算器需要显示货币符号

node.js - PM2:无法访问应用程序(ERR_CONNECTION_REFUSED)

node.js - Mocha + Chai 命令行退出,错误代码编号等于测试失败计数

unit-testing - 有没有办法定义两个不同 Testng Listener 的运行顺序?