Chai Http Post : save entity to mongodb Error: read ECONNRESET

Chai Http Post : save entity to mongodb Error: read ECONNRESET

我正在为将实体保存到 mongodb 的路由编写测试。 该路由在使用 postman 时工作正常,但在运行 chai http test 时失败。

抛出的错误是:

Error: read ECONNRESET

或者有时:

Error: socket hang up.

我不明白我做错了什么,如果有人能帮助我或给我指明方向,我将不胜感激。 干杯

服务器文件:

const express = require('express');
const database = require('./controller/databaseController');
const router = require('./routes/router');
const bodyParser = require('body-parser');

const app =  express();
const port = 3000;

app.use(bodyParser.json());

app.use("/", router);

database.connect();

app.listen(port, () => {

    console.log( "serveur launched, listening on port " + port );
    console.log("environment : " + app.settings.env);

});

//export app for testing purpose
module.exports = app;

路线代码:

router.post('/savePharmacie', (req, res) => {

    var pharmacie = new PharmacieModel(req.body);

    pharmacie.save((err, doc) => {

        if(err){

            res.writeHead(500, {"Content-Type": "application/json"});
            res.json(err);
            res.end();

        }else{

            res.writeHead(200, {"Content-Type": "application/json"});
            res.json(doc);
            res.end();

        }

    });

});

测试代码:

describe('save to database', () => {

    it('save one to database', (done) => {

        chai.request(app)
        .post('saveData/savePharmacie')
        .send(pharmacieMockup)
        .end((err, resp,  body) => {

            if(err){

                console.log("error : " + err);

                done(err);

            }else{

                var response = res.body;     
                console.log("response : " + response);               
                var expected = [pharmacieMockup];                    

                response.should.be.a('array');
                expect(response[0]).to.deep.include(expected[0]);

                done();


            }

        });


    });

    after((done) => {

        PharmacieModel.deleteMany({});
        done();

    });


});

pharmacieMockup 对象是一个虚拟 json 对象,它遵循猫鼬模式。

app 对象引用了一个快速服务器实例。

测试的路线('saveData/savePharmacie')是上面描述的路线(router.post)。

您的第一个问题是由 app.listen 函数引起的:这是一个异步函数,因此当您导入主服务器文件时,您无法确定它是 运行ning。

然后,chai http lib 文档说:

You may use a function (such as an express or connect app) or a node.js http(s) server as the foundation for your request. If the server is not running, chai-http will find a suitable port to listen on for a given test.

因此,我建议您 separate your express app and server 使用两个文件:这样您就可以在测试中导入您的 Express 应用程序,而无需处理外部异步函数。

这是建议结构的最小示例:

文件app.js:

const app = express();
app.get('/', function(req, res) {
  res.status(200);
});
module.exports = app

文件bin/app(没有扩展名的文件):

#!/usr/bin/env node

// the above line is required if you want to make it directly executable
// to achieve this you need to make it executable using "chmod +x bin/app"  from you shell, but it's an optional only required if you want to run it using "./bin/app" without an npm script.

var app = require('../app');
var http = require('http');

app.set('port', process.env.PORT || '3000');

var server = http.createServer(app);

然后使用新的 运行 脚本更新您的 package.json 文件:

"scripts": {
  //...
  "start-app": "node ./bin/app",
}

现在您可以 运行 您的应用程序使用 npm run start-app。您的测试代码应该保持不变,仅使用 require 命令导入 app.js 文件。