Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Index.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

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();
        });
    });
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

You're calling your anonymous async 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...