在摩卡上运行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'); }); ... }) }); 

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

 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) 

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

可能有很多方法来解决这个问题,但是我不认为摩卡或超级用户可以访问导致500发生的实际错误。

你用什么来创buildapp ? 例如,如果是Express,那么在testing过程中可以添加error handling中间件 ,这会导致任何500个诱发错误logging到控制台。

您可以让您的testing代码侦听进程将引发的uncaughtException事件。 只要快速应用程序在与testing工具相同的进程中完成其所有处理,则将在进程中将未处理的exception发送到进程uncaughtException事件处理程序。 现在,这里可能会有点棘手。 因为它是基于事件的,所以任何时候都可以触发一个未处理的exception。 因此,如果您希望更加明确,并且只想处理被测系统中的exception,则需要在运行被测系统代码之前/之后添加/删除监听器。 这是你的例子更新,以侦听未处理的exception。

 import request from 'supertest'; //.... var newGame; describe('Creating game', function() { beforeEach(function(done) { var unhandledException = undefined; var unhandledExceptionCallback = function(err) { unhandledException = err; } process.on('uncaughtException', unhandledExceptionCallback); request(app) .post('/api/games') .send({ owner: 'Mr. X', }) .expect(201) .expect('Content-Type', /json/) .end((err, res) => { process.removeListener('uncaughtException', unhandledExceptionCallback); if (unhandledException !== undefined){ return done(unhandledException); } else 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'); }); ... }) });