node.jsexpressjestjssupertesteconnrefused

Jest test failing with 'connect ECONNREFUSED 127.0.0.1:80' when app is listening on port 3000 (express and supertest)


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.

My issue

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:

//in app.js
const express = require('express');
const app = express();

app.post('api/1.0/users', (req, res) => {
  return res.send();
});

module.exports = app;

//in index.js
const app = require('./app');
const port = 3000;

app.listen(port, () => console.log(`listening on port: ${port}`));

When I run the server, it successfully runs on port 3000. However when I run the following test:

//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) => {
  request(app)
    .post('api/1.0/users')
    .send({
      first_name: 'person',
      last_name: 'one',
      password: '123',
    })
    .expect(200, done);
});

The Problem

I get the error connect ECONNREFUSED 127.0.0.1:80.

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.

What I have attempted

it('returns 200 OK when sign-up request is valid', async () => {
  const response = await request(app).post('api/1.0/users')
  .send({
      first_name: 'person',
      last_name: 'one',
      password: '123',
    })
  expect(response.statusCode).toEqual(200);
});

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.

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).


Solution

  • The problem is the URI. I just tried a test that url does not start using / and got the same error. So instead

    .post('api/1.0/users')
    

    to use

    .post('/api/1.0/users')
    

    may solve the problem.