title: Node.js - Getting "Error: connect ECONNREFUSED" when testing express app with mocha
body: <p>First of all, I'm not listening on port 80 or 8080. I'm listening on port 1337.</p>
  
  <p>I created a simple HTTP server using express. Here is the <em>app.js</em> script to start the server.</p>
  
  <pre><code>require('./lib/server').listen(1337)
  </code></pre>
  
  <p>The server script is located in <code>lib/server.js</code> file, since the same script will also be used in the test script.</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>And, finally the <code>test/test.js</code>:</p>
  
  <pre><code>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()
          })
      })
  
  })
  </code></pre>
  
  <p>But I get a 3/3 errors:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>I really don't understand why this, since my test script seems logic. I ran the server <code>node app.js</code> and tested manually, <code>localhost:1337/john</code> and <code>localhost:1337/sam</code> and it works great!</p>
  
  <p>Any help? Thanks.</p>