Я пишу несколько тестов в Mocha, и мой первый тест всегда проходит:
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: "[email protected]" })
.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.info(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.info("connected to db");
});
app.use(bodyParser.json());
routes(app);
module.exports = app;
приводит к:
[nodemon] starting
mocha --recursive -R min
connected to db1 passing (43ms) 1 failing
1) Drivers controller Post to /api/drivers create a new driver: Error: ECONNREFUSED: Connection refused at Test.assert (node_modules/supertest/lib/test.js:164:13) at Server.assert (node_modules/supertest/lib/test.js:131:12) at emitCloseNT (net.js:1600:8) at processTicksAndRejections (internal/process/next_tick.js:76:17)
[nodemon] app crashed - waiting for file changes before starting...
Не уверен что происходит.
Боже мой, мне пришлось остановить тест, остановить сервер базы данных mongo и перезапустить его, затем запустить тест, и все проходит и работает, как и ожидалось:
connected to db
{ email: '[email protected]' }
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: "[email protected]" })
.set("Accept", "application/json")
.expect("Content-Type", /json/)
.expect(200)
.end(() => {
Driver.count().then(newCount => {
assert(count + 1 === newCount);
done();
});
});
});
});
});