humanbeing
humanbeing

Reputation: 1697

Cannot get node js test to fail

my file structure is like this

folder_main

-server.js

-folder_tests

--serverTest.js

var expect = require("chai").expect;
var http = require('http')

describe('/', function(){
    var server;
    beforeEach(function () {
        server = require('../server');
    });

    afterEach(function () {
        server.close();
    });

    it('should return 200 status code', function(){
        http.get("http://localhost:8080", function(res) {
            console.log("Got response: " + res.statusCode);
            expect(res.statusCode).to.equal("This isnt even a number")
        })
    })
})

and server.js is

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);

var port = 8080;
server.listen(port);
console.log("listening on port " + port)

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

module.exports = server;

when I run "mocha test" from the cmd line I get

 ✓ should return 200 status code
    1) "after each" hook


  1 passing (277ms)   1 failing

  1) / "after each" hook:
     Uncaught Error: connect ECONNRESET
      at errnoException (net.js:904:11)
      at Object.afterConnect [as oncomplete] (net.js:895:19)

I am confused

  1. The first test should fail because it compares to "This isnt even a number".

  2. I am not sure what is happening with Uncaught Error: connect ECONNRESET

Upvotes: 1

Views: 439

Answers (1)

Matt
Matt

Reputation: 74879

Mocha tests need to use the done() callback if you are testing asynchronous code otherwise mocha will complete before your assertions run and no failures will be detected.

it('should return 200 status code', function(done){
    http.get("http://localhost:8080", function(res) {
        console.log("Got response: " + res.statusCode);
        expect(res.statusCode).to.equal("This isnt even a number")
        done()
    })
})

done is setup as the first parameter to your testing function, which you then call after your assertions. If the done function is not called, mocha will timeout the test after the default of 2 seconds.

This will probably resolve your ECONNRESET issue too as your server is not being shutdown mid test/request.

It can help to always make use of done(), even when testing synchronous code so you don't fall into this trap in the future. False positives can cause hours of trouble shooting pain.

Upvotes: 4

Related Questions