Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Getting "Error: connect ECONNREFUSED" when testing express app with mocha

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

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

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

The server script is located in lib/server.js file, 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 the 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 a 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, since my test script seems logic. I ran the server node app.js and tested manually, localhost:1337/john and localhost:1337/sam and it works great!

Any help? Thanks.

like image 387
htaidirt Avatar asked Mar 07 '13 10:03

htaidirt


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()
})
like image 53
Amberlamps Avatar answered Oct 24 '22 03:10

Amberlamps


http.get({path: '/john', port: 1337}, function(res){
    //...
});

Should work. http.get assumes port 80 if nothing else is specified.

like image 21
Andreas Hultgren Avatar answered Oct 24 '22 02:10

Andreas Hultgren