在mocha中运行supertest时如何获得实际的服务器错误?

use*_*715 12 mocha.js node.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');
    });

   ...
  })
});
Run Code Online (Sandbox Code Playgroud)

当服务器代码抛出一些异常(例如访问未定义对象的属性)时,我得到了这个堆栈跟踪

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)
Run Code Online (Sandbox Code Playgroud)

而不是说"访问未定义的属性"之类的实际错误.我怎样才能得到实际的错误?

Atu*_*rma 3

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

你用什么来创造app?例如,如果是 Express,则可以在测试期间添加错误处理中间件,这会导致将任何引发 500 的错误记录到控制台。

例如这样:

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

const request = supertest(app.use(logErrors))
Run Code Online (Sandbox Code Playgroud)