Узел Mocha & Supertest: Ошибка: ECONNREFUSED: соединение отказано - PullRequest
0 голосов
/ 29 июня 2018

Я построил API и хочу протестировать некоторые конечные точки.

У меня есть ряд тестов, похожих на приведенные ниже. Все они терпят неудачу из-за Error: ECONNREFUSED: Connection refused

Тесты

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"

ошибка:

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

Видимо, в соединении отказывают? Но я не уверен, что конкретно это означает, потому что вы можете видеть, что сервер в журнале ошибок подключен, как и служба mongo.

index.ts

import Server from "./server";

export default new Server().server;

server.ts

Импорт приложения из "./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;

1 Ответ

0 голосов
/ 29 июня 2018

Убедитесь, что ваш сервер остановлен, прежде чем запускать тестовый набор, используя supertest, так как supertest запускает API в этом же порту. Таким образом, вы должны сделать этот порт свободным для использования supertest.

Поскольку вы используете это в своем тестовом файле,

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

app содержит URL-адрес домена, такой как http://localhost:3135, и когда вы вызываете API, например, request(app).post, где request относится к модулю supertest, вам всегда нужно убедиться, что app свободно. Это означает, что request('http://localhost:3135').post работает, когда на порту 3135.

не запущен процесс.

Вы можете проверить узел, выполняющий процессы, используя pidof node (в linux) и уничтожить каждый процесс, чтобы убедиться, что порт доступен, или уничтожить процесс для этого конкретного порта.

...