Tuesday 14 March 2017

Trouble Setting Up Mocha/ChaiHttp Unit Tests With My Node.js REST API

I am trying to set up unit testing for my node.js REST API using mocha and chaihttp, but my sample test which should pass seems to be failing.

My code for the unit tests is here:

var express = require('express');
var router = express.Router();

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

describe("Test", function() {
    it('Simple test', function(done) {
        chai.request('http://localhost:3000/')
            .get('/')
            .end(function(err, res) {
                chai.expect(res).to.have.status(200);
                done();
            });
    });
});

And the error I get when running the tests:

  1) Test Simple test:
     Uncaught AssertionError: expected { Object (domain, _events, ...) } to have status code 200 but got 404
      at tests.js:13:42
      at Test.Request.callback (/Users/laptop/Desktop/Toptal/node_modules/superagent/lib/node/index.js:631:3)
      at IncomingMessage.<anonymous> (/Users/laptop/Desktop/Toptal/node_modules/superagent/lib/node/index.js:795:18)
      at endReadableNT (_stream_readable.js:974:12)
      at _combinedTickCallback (internal/process/next_tick.js:74:11)
      at process._tickCallback (internal/process/next_tick.js:98:9)

From what it looks like, it's unable to connect to my local host or something because I'm getting a 404 error whereas if I manually go to localhost:3000 in my browser, I'm served a simple Hello world index page.

Here is my index.js route if it might be relevant:

var express = require('express');

var router = express.Router();

router.get('/', function(req, res, next) {
    res.status(200).render('index.ejs');
});

module.exports = router;



via ilovecoding

No comments:

Post a Comment