5

I have built an api and i want to test some of the endpoints.

I have a number of tests that are similar to the ones below. They are all all failing because of Error: ECONNREFUSED: Connection refused

tests

import { assert, expect } from "chai";
import request from "supertest";
import app from "./../src/index";

describe("Authentication", () => {

    it("should respond with 200 product_id is authorised", async () => {

        const result = await request(app).post("/api/auth")
            .send({
                product_id: "123",
                origin: "localhost:3000",
            })
            .expect("Content-Type", /json/)
            .expect(200);

    });

    it("should respond with session token", async () => {

        const result = await request(app).post("/api/auth")
            .send({
                product_id: "123",
                origin: "localhost:3000",
            });

        expect(result.body.data).to.have.property("token");

    });
});

package.json

"test": "mocha -r ts-node/register --project tsconfig.json test/*.test.ts --exit"

errors:

> mocha -r ts-node/register --project tsconfig.json test/*.test.ts --exit

Server Running On: runner-sefsf-project-41-concurrent-0gdrs7:3000


  Authentication
MongoDB Successfully Connected On: mongodb://localhost:27017/p
    1) should respond with 200 product_id is authorised
    2) should respond with p session token

  Server
    3) should be up
    4) should throw 404 for unrecognized routes

  Transaction
    5) should respond with a new transction


  0 passing (40ms)
  5 failing

  1) Authentication
       should respond with 200 product_id is authorised:
     Error: ECONNREFUSED: Connection refused
      at Test.assert (node_modules/supertest/lib/test.js:165:15)
      at assert (node_modules/supertest/lib/test.js:131:12)
      at /eng/p-server/node_modules/supertest/lib/test.js:128:5
      at Test.Request.callback (node_modules/superagent/lib/node/index.js:718:3)
      at ClientRequest.req.once.err (node_modules/superagent/lib/node/index.js:646:10)
      at Socket.socketErrorListener (_http_client.js:382:9)
      at emitErrorNT (internal/streams/destroy.js:82:8)
      at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
      at process._tickCallback (internal/process/next_tick.js:63:19)

  2) Authentication
       should respond with p session token:
     Error: ECONNREFUSED: Connection refused
      at Test.assert (node_modules/supertest/lib/test.js:165:15)
      at assert (node_modules/supertest/lib/test.js:131:12)
      at /eng/p-server/node_modules/supertest/lib/test.js:128:5
      at Test.Request.callback (node_modules/superagent/lib/node/index.js:718:3)
      at ClientRequest.req.once.err (node_modules/superagent/lib/node/index.js:646:10)
      at Socket.socketErrorListener (_http_client.js:382:9)
      at emitErrorNT (internal/streams/destroy.js:82:8)
      at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
      at process._tickCallback (internal/process/next_tick.js:63:19)

Apparently the connection is being refused? But i'm not sure what it means by this specifically because you can see the server in the error log is connected and so is the mongo service.

index.ts

import Server from "./server";

export default new Server().server;

server.ts

import App from "./app";

class Server {

    public server: any;
    private instance: any;
    private app: any;
    private config: any;

    constructor() {

        this.instance = new App();
        this.app = this.instance.app;
        this.config = this.instance.config;
        this.server = this.app.listen(this.config.port, this.config.hostname);

        console.log("Server Running On: " + this.config.hostname + ":" + this.config.port);

    }

}

export default Server;
Kay
  • 17,906
  • 63
  • 162
  • 270
  • 1
    Posting [same question](https://stackoverflow.com/questions/51087753/nodejs-mocha-chai-supertest-async-tests-failing) multiple times isn't considered a good practice. If you feel your problem is important, consider offering a bounty. Even in this case, the case is complex and needs a way to replicate the problem - a repo, etc. – Estus Flask Jun 29 '18 at 10:39
  • @estus thanks i forgot to delete the old one – Kay Jun 29 '18 at 10:42

2 Answers2

4

Make sure your server is stopped before you run the test case using supertest as supertest run the api in that same port. So, you need to make that port free for use by supertest.

Since you are using this in your test file,

import request from "supertest";
import app from "./../src/index";

The app contains the domain URL like http://localhost:3135 and when you call the api like, request(app).post where request refers to the supertest module, you always need to make sure that the app is free. Which means, request('http://localhost:3135').post works when there is no process running on port 3135.

You can check the node running processes using pidof node (in linux)and kill every process to make sure the port is available or kill process for that specific port.

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • I am just running this single npm command. `"test": "mocha -r ts-node/register --project tsconfig.json test/*.test.ts --exit"` – Kay Jun 29 '18 at 10:10
  • However it is being run through gitlab ci. – Kay Jun 29 '18 at 10:13
  • @Kay added more detail in answser. Hope that will help you. – Ankit Agarwal Jun 29 '18 at 10:16
  • It uses port 3000, are you suggesting in the docker image something else might be using port 3000? – Kay Jun 29 '18 at 10:19
  • Where does the test fails? In your local or in ci? @Kay – Ankit Agarwal Jun 29 '18 at 10:19
  • In my CI, locally its fine. – Kay Jun 29 '18 at 10:19
  • So the gitlab ci hasn't been configured properly. Are there multiple projects in ci? If yes, you need to make sure all of them has unique port – Ankit Agarwal Jun 29 '18 at 10:20
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174025/discussion-between-kay-and-ankit-agarwal). – Kay Jun 29 '18 at 10:20
  • Incase someone comes across this post, this answer did not work for me. There was nothing running on the same port – Kay Jun 29 '18 at 14:02
  • @Kay This should have worked for you. Because the same has worked for me in my local. There must be surely something missing on your side. That is why it is behaving weird. – Ankit Agarwal Jun 29 '18 at 15:26
  • I am facing issue with `http://localhost:4000` in test, while the same test pass with `http://127.0.0.1:4000`. But from terminal both are working fine. https://github.com/visionmedia/supertest/issues/484#issuecomment-1164757735 – Vladimir Vukanac Jun 23 '22 at 19:05
1

I encountered the same error and spend a couple of hours trying to figure out what was up. I was using the pg library and so it happens it needs to pick db options from the environment variables. My problem was I was calling dotenv.config() at the wrong place.

Dev Yego
  • 539
  • 2
  • 12