Jest test passed but get Error: connect ECONNREFUSED 127.0.0.1:80 at the end

30,051

Solution 1

So I figured out and the solution is quite easy. I can't explain why though.

This req.get('api/v1/users/') should be /api/v1/users - you need a leading /.

Solution 2

For Frontend...

If you are making use of axios and come across this error, go to the testSetup.js file and add this line

axios.defaults.baseURL = "https://yourbaseurl.com/"

This worked for me. So, typically, this is a baseURL issue.

Solution 3

Slightly different issue, but same error message...

I was having this error when using node-fetch when trying to connect to my own localhost (http://localhost:4000/graphql), and after trying what felt like everything under the sun, my most reliable solution was:

using this script in package.json: "test": "NODE_ENV=test jest --watch" If the terminal shows connection error I just go to the terminal with Jest watching and press a to rerun all tests and they pass without any issue.

¯\_(ツ)_/¯

Success rate continued to improve by renaming the testing folder to __tests__ and moving my index.js to src/index.js.

Very strange, but I am too exhausted to look at the Jest internals to figure out why.

Share:
30,051
aRtoo
Author by

aRtoo

Updated on March 21, 2022

Comments

  • aRtoo
    aRtoo about 2 years

    I'm using node with TypeScript on my back end and Jest and Supertest as my test framework on my back end.

    When I'm trying to test I have the result pass but I get an error at the end. Here's the result:

     PASS  test/controllers/user.controller.test.ts
      Get all users
        ✓ should return status code 200 (25ms)
    
      console.log node_modules/@overnightjs/logger/lib/Logger.js:173
        [2019-12-05T04:54:26.811Z]: Setting up database ...
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        3.284s
    Ran all test suites.
    server/test/controllers/user.controller.test.ts:32
                    throw err;
                    ^
    
    Error: connect ECONNREFUSED 127.0.0.1:80
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
    npm ERR! Test failed.  See above for more details.
    

    Here's my test code:

    import request from "supertest";
    import { AppServer } from '../../config/server';
    
    const server = new AppServer();
    
    describe('Get all users', () => {
      it('should return status code 200', async () => {
        server.startDB();
        const appInstance = server.appInstance;
        const req = request(appInstance);
        req.get('api/v1/users/')
          .expect(200)
          .end((err, res) => {
            if (err) throw err;
          })
      })
    })
    

    Here's my server setup. I'm using overnightjs on my back end.

    I created a getter to get the Express instance. This is coming from overnight.js.

    // this should be the very top, should be called before the controllers
    require('dotenv').config();
    
    import 'reflect-metadata';
    
    import { Server } from '@overnightjs/core';
    import { Logger } from '@overnightjs/logger';
    import { createConnection } from 'typeorm';
    import helmet from 'helmet';
    import * as bodyParser from 'body-parser';
    import * as controllers from '../src/controllers/controller_imports';
    
    export class AppServer extends Server {
      constructor() {
        super(process.env.NODE_ENV === 'development');
        this.app.use(helmet());
        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({ extended: true }));
        this.setupControllers();
      }
    
      get appInstance(): any {
        return this.app;
      }
    
      private setupControllers(): void {
        const controllerInstances = [];
    
        // eslint-disable-next-line
        for (const name of Object.keys(controllers)) {
          const Controller = (controllers as any)[name];
          if (typeof Controller === 'function') {
            controllerInstances.push(new Controller());
          }
        }
    
        /* You can add option router as second argument */
        super.addControllers(controllerInstances);
      }
    
      private startServer(portNum?: number): void {
        const port = portNum || 8000;
        this.app.listen(port, () => {
          Logger.Info(`Server Running on port: ${port}`);
        });
      }
    
      /**
       * start Database first then the server
       */
      public async startDB(): Promise<any> {
        Logger.Info('Setting up database ...');
        try {
          await createConnection();
          this.startServer();
          Logger.Info('Database connected');
        } catch (error) {
          Logger.Warn(error);
          return Promise.reject('Server Failed, Restart again...');
        }
      }
    }
    
    

    I read this question - that's why I called the method startDB.

  • LSR
    LSR almost 4 years
    Though I wouldn't go into a global file I find this information very useful. Thank you. :)
  • Native Coder
    Native Coder over 3 years
    It makes complete sense that this works. here is why: webmasters.stackexchange.com/questions/56840/…
  • Artan M.
    Artan M. about 3 years
    Thank you, this fixed it for me. Just wanted to add that you need to import import axios from "axios"; before setting the default baseURL.