Search code examples
node.jsmocha.jschaichai-http

Mocha and Chai with NodeJS, simple server test failing with a 404 (should be 200)


I have wrote a simple test using Mocha and Chai. The test is returning as failed. After changing to my correct test directory and running npm test the error returned is the below. Please can someone help me figure out why 9000 is already in use?

1) Uncaught error outside test suite
  SERVER TESTS
    2) Should list all of the /gets


  0 passing (43ms)
  2 failing

  1) Uncaught error outside test suite:
     Uncaught Error: listen EADDRINUSE: address already in use :::9000
  2) SERVER TESTS
       Should list all of the /gets:

      Uncaught AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
      + expected - actual

      -404
      +200

test.js

// Unit tests for my server using Mocha and Chai

var chai = require("chai");
var chaiHttp = require("chai-http");
var server = require("../hangman-server.js");
var should = chai.should();

chai.use(chaiHttp);


describe("SERVER TESTS", function() {

    it("Should list all of the /gets", function(done) {
        chai.request(server)
        .get("/get")
        .end(function(err, res){
          res.should.have.status(200);
          done();
        });
    });

});

hangman-server.js

// Creating a listener on the specified port
server.listen(port, async function() {
    // Connect to Mongoose.
    await mongoose.connect(uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
    console.log("Connected to DB");

    // Output for terminal, 9000 should display in place of the port
    console.log("Listening on " + port);
})

app.get("/", function(request, response) {
    response.status(200).sendFile("/", {root: "client"});
});

My package.json which includes mocha and chai

{
  "name": "SOFT355-HangMan",
  "version": "1.0.0",
  "description": "",
  "main": "._hangman-server.js",
  "directories": {
    "test": "test"
  },
  "dependencies": {
    "angular": "^1.7.9",
    "chai": "^4.2.0",
    "chai-http": "^4.3.0",
    "express": "^4.17.1",
    "http": "^0.0.0",
    "mocha": "^6.2.2",
    "mongoose": "^5.7.13",
    "nodemon": "^2.0.2",
    "websocket": "^1.0.30",
    "websocket.io": "^0.2.1"
  },
  "scripts": {
    "test": "mocha",
    "dev": "nodemon hangman-server.js",
    "start": "node hangman-server.js",
    "server": "nodemon hangman-server.js"
  },

Solution

  • The reason for the Error: listen EADDRINUSE: address already in use :::9000 error is because of you run npm start in one terminal and after that npm test in another terminal. So npm start starts one server and the require("../hangman-server.js"); in your test tries to start another server on the same port and that results in this error message.

    About the 404, you request /get but your server will only respond for / because app.get("/", will register the middleware for an exact match of /.