npm test returns internal server error while npm start just works

255 views Asked by At

I am running into an error that occurs with a npm chai .should() test

1) GET /api/v1/users should respond with all users:
     Uncaught AssertionError: expected [Error: Internal Server Error] to not exist
      at Object.should.not.exist (node_modules/chai/lib/chai/interface/should.js:190:38)
      at chai.request.get.end (test/integration/routes.users.test.js:41:18)
      at Test.Request.callback (node_modules/superagent/lib/node/index.js:631:3)
      at node_modules/superagent/lib/node/index.js:795:18
      at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/parsers/json.js:16:7)
      at endReadableNT (_stream_readable.js:1055:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

When I request the "/api/v1/users" route when running the app no error occurs. Is something wrong with the test?

process.env.NODE_ENV = 'test';

var chai = require('chai'),
should = chai.should(),
chaiHttp = require('chai-http');
chai.use(chaiHttp);

var server = require('../../src/server/app'),
knex = require('../../src/server/db/knex');

describe('routes : users', () => {

  beforeEach((done) => {
    knex.migrate.rollback()
    .then(() => {
      knex.migrate.latest() // use latest table migration
      .then(() => {
        knex.seed.run() // seed the db table
        .then(() => {
          done();
        })
      });
    });
  });

  afterEach((done) => {
    knex.migrate.rollback() // reverses migration
    .then(() => {
      done();
    });
  });

});

describe('GET /api/v1/users', () => {
  it('should respond with all users', (done) => {
    chai.request(server)
    .get('/api/v1/users')
    .end((err, res) => {
      // there should be no errors
      should.not.exist(err);
      // there should be a 200 status code
      res.status.should.equal(200);
      // the response should be JSON
      res.type.should.equal('application/json');
      // the JSON response body should have a
      // key-value pair of {"status": "success"}
      res.body.status.should.eql('success');
      // the JSON response body should have a
      // key-value pair of {"data": [2 user objects]}
      res.body.data.length.should.eql(2);
      // the first object in the data array should
      // have the right keys
      res.body.data[0].should.include.keys(
        'id', 'username', 'email', 'created_at'
      );
      done();
    });
  });
});

Credits to Michael Herman whose Testing Node and Express tutorial I am following.

Please check my repo here.

1

There are 1 answers

0
Wasbeer On

Solved! I did not apply the migration and run the seed in the test environment:

knex migrate:latest --env test
knex seed:run --env test