Ошибка соединения отклонена, когда Mongo подключен к приложению - PullRequest
0 голосов
/ 27 мая 2019

Я пишу несколько тестов в Мокко, и мой первый тест всегда проходит:

const assert = require('assert');
const request = require('supertest');
const app = require('../app');

describe('The express app', () => {
  it('handles a GET request to /api', done => {
    request(app)
      .get('/api')
      .end((err, response) => {
        assert(response.body.hi === 'there');
        done();
      });
  });
});

Но этот второй тест всегда не проходит с момента его создания:

const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", () => {
    let oldCount;
    return Driver.count()
      .then(count => {
        oldCount = count;
        return new Promise((resolve, reject) => {
          request(app)
            .post("api/drivers")
            .send({ email: "test@test.com" })
            .end((err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve(res);
              }
            });
        });
      })
      .then(() => {
        return Driver.count();
      })
      .then(newCount => {
        assert(oldCount + 1 === newCount);
      });
  });
});

Выше приведен третий рефакторинг, и я тестирую этот контроллер:

const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};

С оригинальным рефакторингом я понял, что assert(oldCount + 1 === newCount); возвращает falsy вместо truthy, чего не ожидалось, и с рефактором моего теста я получаю отказ в соединении, но БД подключен, с которым я проверял эта конфигурация:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

const connection = mongoose.connection;

connection.on("connected", function() {
  console.log("connected to db");
});

app.use(bodyParser.json());
routes(app);

module.exports = app;

Результат:

[nodemon] начиная с mocha --recursive -R min подключено к БД

1 прохождение (43мс) 1 сбой

1) Контроллер драйверов Опубликовать в / api / drivers создать новый драйвер: Ошибка: ECONNREFUSED: соединение отказано в Test.assert (node_modules / supertest / lib / test.js: 164: 13) в Server.assert (node_modules / supertest / lib / test.js: 131: 12) at emitCloseNT (net.js: 1600: 8) at processTicksAndRejected (внутренняя / process / next_tick.js: 76: 17)

Сбой приложения [nodemon] - ожидание изменений файла перед запуском ...

Не уверен, что происходит.

1 Ответ

0 голосов
/ 27 мая 2019

Святая корова, мне пришлось остановить тест и остановить сервер баз данных mongo и перезапустить его, затем запустить тест, и все проходит и работает, как и ожидалось:

  connected to db
{ email: 'test@test.com' }

  2 passing (132ms)

[nodemon] clean exit - waiting for changes before restart

Рефакторинг фактически не был необходим, ноЯ немного подправил его, вернув обратно на:

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("/api/drivers")
        .send({ email: "test@test.com" })
        .set("Accept", "application/json")
        .expect("Content-Type", /json/)
        .expect(200)
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});
...