【问题标题】:Testing Express Js Server using mocha and chai使用 mocha 和 chai 测试 Express Js 服务器
【发布时间】:2021-01-12 17:51:02
【问题描述】:

我正在尝试使用 mocha 和 chai 测试我的 express 服务器,但测试完成后我无法关闭服务器连接。

索引.js

const express = require('express');
const dbconnection = require('./dbConnection.js');

const app = express();
.....

(async ()=>{
 await dbconnection.init();

/* Loading middleware and stuff */

 const server = app.listen(port, host, ()=>{
   console.log('Server Started!')
   app.emit('ready');
});
})()

module.exports = app;

我想知道如何在测试执行后关闭服务器。目前正在测试,但测试后它挂起。

server.test.js

const server = require("../../index");
const chai = require("chai");
const chaiHttp = require("chai-http");
const should = chai.should();
chai.use(chaiHttp);

before(function (done) {
  this.timeout(15000);
  server.on("ready", () => {
    done();
  });
});

describe.only("Health Check Test", function () {
  describe("/GET healthy", () => {
    it("it should GET the health status", (done) => {
      chai
        .request(server)
        .get("/healthy")
        .end((error, res) => {
          res.should.have.status(200);
          done();
        });
    });
  });
});

【问题讨论】:

    标签: javascript node.js express mocha.js chai


    【解决方案1】:

    您正在调用匿名异步函数。要解决这个问题,您不需要内联调用它,而是在另一个文件中调用它:

    // index.js
    const app = express()
    
    const startApp = async () => {
      await dbconnection.init();
    
      const server = app.listen(port, host, ()=>{
        console.log('Server Started!')
        app.emit('ready');
      });
    }
    
    module.exports = { app, startApp }
    
    // server.test.js
    const { app: server } = requre('../../')
    
    // index.boot.js, or start.js, or something else
    require('./index').startApp()
    

    如果您在测试期间最终需要数据库连接,您还需要将其从调用 app.listen 的函数中移除,以便您可以在测试中将其关闭。

    【讨论】:

    • 如何关闭应用程序?这就是问题..我无法调用 app.close
    • 对于实际关闭,您可以使用http.createServerdone,或使用chai.request(server).close(),如答案here
    • 如果我调用 chai.request(server).close 我想我会得到“不是函数”异常。我猜 .close 仅​​适用于从侦听器返回的内容
    猜你喜欢
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多