Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the actual server error when running supertest in mocha?

I have this code using supertest and 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');
    });

   ...
  })
});

When the server code throws some exception (e.g. accessing properties of an undefined object) I get this stack trace

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)

instead of the actual error that says something like "accessing properties of undefined". How can I get the actual error?

like image 915
user69715 Avatar asked Jan 09 '16 22:01

user69715


People also ask

What is SuperTest in mocha?

SuperTest is a Node. js library that helps developers test APIs. It extends another library called superagent, a JavaScript HTTP client for Node. js and the browser. Developers can use SuperTest as a standalone library or with JavaScript testing frameworks like Mocha or Jest.

What does SuperTest request do?

SuperTest provides a high-level abstraction for testing HTTP requests - perfect for APIs. If you have a Node. js application that runs an HTTP server (like an Express application), you can make requests using SuperTest directly without needing a running server.


1 Answers

There are probably a lot of ways to tackle this, but I don't believe mocha or supertest have access to the actual error that caused the 500 to occur.

What are you using to create app? If it's Express, for example, error-handling middleware can be added during testing which causes any 500-inducing errors to be logged to the console.

like this for example:

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

const request = supertest(app.use(logErrors))
like image 163
Atul Varma Avatar answered Sep 20 '22 22:09

Atul Varma