node.js - 在 mocha 中运行 supertest 时如何获取实际的服务器错误?

标签 node.js mocha.js supertest

我有这段代码使用 supertest 和 mocha:

import request from 'supertest';

//....

var newGame;
describe('Creating game', function() {
  beforeEach(function(done) {
    request(app)
      .post('/api/games')
      .send({
        owner: 'Mr. X',
      })
      .expect(201)
      .expect('Content-Type', /json/)
      .end((err, res) => {
        if (err) {
          return done(err);
        }
        newGame = res.body;
        done();
      });
  });    

  describe('the created game', function() {

    it('should name the specified owner', function() {
      newGame.owner.should.equal('Mr. X');
    });

   ...
  })
});

当服务器代码抛出一些异常(例如访问 undefined object 的属性)时,我会得到这个堆栈跟踪

Error: expected 201 "Created", got 500 "Internal Server Error"
  at Test._assertStatus (D:\Codes\theApp\node_modules\supertest\lib\test.js:232:12)
  at Test._assertFunction (D:\Codes\theApp\node_modules\supertest\lib\test.js:247:11)
  at Test.assert (D:\Codes\theApp\node_modules\supertest\lib\test.js:148:18)
  at Server.assert (D:\Codes\theApp\node_modules\supertest\lib\test.js:127:12)
  at emitCloseNT (net.js:1521:8)

而不是实际的错误,例如“访问未定义的属性”。我怎样才能得到实际的错误?

最佳答案

可能有很多方法可以解决这个问题,但我认为 mocha 或 supertest 无法访问导致 500 发生的实际错误。

你用什么来创建app?如果是 Express,例如 error-handling middleware可以在测试期间添加,这会导致将任何 500 诱导错误记录到控制台。

例如这样:

function logErrors (err, req, res, next) {
  console.error(err.stack)
  next(err)
}

const request = supertest(app.use(logErrors))

关于node.js - 在 mocha 中运行 supertest 时如何获取实际的服务器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34699457/

相关文章:

javascript - 创建一个 Node.js 可写流,将数据代理到另一个可写流,但首先在其前面添加一些自己的数据

javascript - _typeof 函数降低了工作服测试百分比

javascript - 使用 Mocha 和 Sinon 测试 anchor 链接调用

javascript - Mocha with Blanket、Babel 和 LCOV 记者

javascript - 尝试通过模拟管道函数来测试文件检索

node.js - 防止 Angular 6 路由器覆盖 Express Server 中定义的路由

node.js - 我安装了 node.js v5.12.0 但版本显示为 v0.12.2

node.js - 在 node.js 服务器上使用 supertest/superagent 读取响应输出缓冲区/流

javascript - ejs获取嵌套对象

node.js - Supertest + Knex.js = 当前客户端上没有定义池