Node.js - Getting "Error: connecting ECONNREFUSED" when testing express application with mocha

First of all, I am not listening on port 80 or 8080. I am listening on port 1337.

I created a simple HTTP server using express. Here is the app.js script application to start the server.

require('./lib/server').listen(1337) 

The script server is located in the lib/server.js , since the same script will also be used in the test script.

 var http = require('http') , express = require('express') , app = express() app.get('/john', function(req, res){ res.send('Hello John!') }) app.get('/sam', function(req, res){ res.send('Hello Sam!') }) module.exports = http.createServer(app) 

And finally, test/test.js :

 var server = require('../lib/server') , http = require('http') , assert = require('assert') describe('Hello world', function(){ before(function(done){ server.listen(1337).on('listening', done) }) after(function(){ server.close() }) it('Status code of /john should be 200', function(done){ http.get('/john', function(res){ assert(200, res.statusCode) done() }) }) it('Status code of /sam should be 200', function(done){ http.get('/sam', function(res){ assert(200, res.statusCode) done() }) }) it('/xxx should not exists', function(done){ http.get('/xxx', function(res){ assert(404, res.statusCode) done() }) }) }) 

But I get 3/3 errors:

 Hello world 1) Status code of /john should be 200 2) Status code of /sam should be 200 3) /xxx should not exists βœ– 3 of 3 tests failed: 1) Hello world Status code of /john should be 200: Error: connect ECONNREFUSED at errnoException (net.js:770:11) at Object.afterConnect [as oncomplete] (net.js:761:19) 2) Hello world Status code of /sam should be 200: Error: connect ECONNREFUSED at errnoException (net.js:770:11) at Object.afterConnect [as oncomplete] (net.js:761:19) 3) Hello world /xxx should not exists: Error: connect ECONNREFUSED at errnoException (net.js:770:11) at Object.afterConnect [as oncomplete] (net.js:761:19) 

I really don't understand why this is, since my test script seems logical. I started the node app.js server and manually tested localhost:1337/john and localhost:1337/sam and it works great!

Any help? Thanks.

+8
testing express mocha
source share
2 answers

For http.get() to work, you need to assign the full path to the resource as the first argument:

 http.get('http://localhost:1337/john', function(res){ assert(200, res.statusCode) done() }) 
+8
source share
 http.get({path: '/john', port: 1337}, function(res){ //... }); 

Must work. http.get assumes port 80 if nothing is specified.

+5
source share

All Articles