1

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

1 Answers1

0

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.

Zac Anger
  • 6,983
  • 2
  • 15
  • 42
  • How can i close the app? That is the problem..i cant call app.close – DevDesignerSid Jan 12 '21 at 18:21
  • For the actual closing, you can either use `http.createServer` with `done`, or use `chai.request(server).close()` as in the answers [here](https://stackoverflow.com/questions/49789886/how-to-correctly-close-express-server-between-tests-using-mocha-and-chai). – Zac Anger Jan 12 '21 at 18:32
  • If i call chai.request(server).close i think i will get 'not a function' exception. I guess .close is only available for what is returned from listener – DevDesignerSid Jan 12 '21 at 19:29