Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 215
aRtoo Avatar asked Dec 05 '19 05:12

aRtoo


1 Answers

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

like image 82
aRtoo Avatar answered Sep 18 '22 12:09

aRtoo