title: Jest test failing with 'connect ECONNREFUSED 127.0.0.1:80' when app is listening on port 3000 (express and supertest)
body: <p>I am struggling to resolve a bug in my jest test using supertest, I think it is an issue with my test rather than my code.</p>
  <p><strong>My issue</strong></p>
  <p>I am trying to create a back end API using node.js and express, using TDD. I have the following files to set up the server:</p>
  <pre><code>//in app.js
  const express = require('express');
  const app = express();
  
  app.post('api/1.0/users', (req, res) =&gt; {
    return res.send();
  });
  
  module.exports = app;
  
  //in index.js
  const app = require('./app');
  const port = 3000;
  
  app.listen(port, () =&gt; console.log(`listening on port: ${port}`));
  </code></pre>
  <p>When I run the server, it successfully runs on port 3000. However when I run the following test:</p>
  <pre><code>//in UserRegister.test.js
  const request = require('supertest');
  const app = require('../app'); //this is in a __tests__ subdir hence '..'
  
  it('returns 200 OK when sign-up request is valid', (done) =&gt; {
    request(app)
      .post('api/1.0/users')
      .send({
        first_name: 'person',
        last_name: 'one',
        password: '123',
      })
      .expect(200, done);
  });
  </code></pre>
  <p><strong>The Problem</strong></p>
  <p>I get the error <code>connect ECONNREFUSED 127.0.0.1:80</code>.</p>
  <p>I think this is telling me that the test is looking to connect to port 80, however there is no server set up on port 80 so the connection is refused, but it should be trying to connect to port 3000.</p>
  <p><strong>What I have attempted</strong></p>
  <ul>
  <li>All packages are appropriately installed to the best of my knowledge</li>
  <li>I tried a hacky solution of getting my server to listen on port 80 but that raises the same issue.</li>
  <li>reading the supertest docs to try alternate solutions</li>
  <li>Tried the following different syntax in case it was an obvious syntax issue I was misinterpreting:</li>
  </ul>
  <pre><code>it('returns 200 OK when sign-up request is valid', async () =&gt; {
    const response = await request(app).post('api/1.0/users')
    .send({
        first_name: 'person',
        last_name: 'one',
        password: '123',
      })
    expect(response.statusCode).toEqual(200);
  });
  </code></pre>
  <p>What am I missing? I am increasingly confident it is my lack of understanding of how supertest works but I can't seem to understand what the issue is.</p>
  <p>I am simply looking for the test to either pass or fail (either by getting a 200 or 404 response), but only once it has connected to the correct port (i.e. I am stuck the first hurdle).</p>