bloppit
bloppit

Reputation: 641

Why isn't my express test passing?

I'm attempting to set up a server with Node/Express and want to be able to write ES6 so I'm using babel.

Right now, the server is working and I'm able to make the requests I need but I'm trying to set up a test for it in case I want to make any modifications. The test is failing for a reason I cannot yet ascertain.

Here is my code,

App.js:

import express from 'express';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import router from './routes/router';

// App Setup
const app = express();
app.use(morgan('combined'));
app.use(bodyParser.json({ type: '*/*' }));
router(app);

export default app;

Index.js:

import app from './app';

// Server Setup
const port = process.env.PORT || 3090;
app.listen(port, () => {
    console.log(`Server listening on: ${port}`);
});

Router.js:

const router = (app) => {
  app.get('/', (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World\n');
  });
};

export default router;

The test.js:

import assert from 'assert';
import request from 'supertest';
import app from '../app';

describe('The express App', () => {
  it('should return 200', done => {
    request(app)
      .get('/')
      .end((res) => {
        assert.equal(200, res.statusCode);
        done();
    });
  });
});

Here is the npm script:

"test": "mocha --compilers js:babel-register",

And the result I'm getting is this: enter image description here

Can you please tell me what I'm doing wrong here? Thanks!

Upvotes: 3

Views: 44

Answers (2)

Lyubomir
Lyubomir

Reputation: 20037

Because first argument of the end callback is err, which in your case is undefined and results in

assert.equal(200, undefined.statusCode)

The right way

.end((err, res) => {
   if (err) return done(err);
   assert.equal(200, res.statusCode);
   done();
})

Even better would be to use directly .expect(200) as answered by @R. Gulbrandsen.

Upvotes: 2

R. Gulbrandsen
R. Gulbrandsen

Reputation: 3778

Try to change your test to use the supertest's expect like this:

import assert from 'assert';
import request from 'supertest';
import app from '../app';

describe('The express App', () => {
  it('should return 200', done => {
    request(app)
      .get('/')
      .expect(200)
      .end(done);
  });
});

Upvotes: 2

Related Questions