简体   繁体   English

使用 mocha 和 chai 测试 Express Js 服务器

[英]Testing Express Js Server using mocha and chai

I'm trying to test my express server using mocha and chai but i'm not able to close the server connection once the test has been completed.我正在尝试使用 mocha 和 chai 测试我的快速服务器,但测试完成后我无法关闭服务器连接。

Index.js索引.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;

I would like to know how to close the server once the test is executed.我想知道执行测试后如何关闭服务器。 Currently testing is working but after the test it hangs.目前测试正在工作,但在测试后它挂起。

server.test.js 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();
        });
    });
  });
});

You're calling your anonymous async function.您正在调用匿名异步 function。 To fix this, you would need to not call it inline, and call it in another file:要解决这个问题,您不需要内联调用它,而是在另一个文件中调用它:

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

If you end up needing the database connection during tests, you would need to also lift that up out of the function that calls app.listen so you can close it in your tests.如果您在测试期间最终需要数据库连接,您还需要将其从调用app.listen的 function 中取出,以便您可以在测试中关闭它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM