10

I have a jest supertest setup for my testing , I am trying to close server after tests are done but it is throwing error, it is saying server.close() is not a function. what is wrong here? is it issue with express or jest or supertest I am not able to figure it out I am new to testing please help me.

server.js file:

const next = require("next");
const express = require("express");
const winston = require("winston");
const config = require("config");
const passport = require("passport");
const flash = require("connect-flash");
const path = require("path");
var cookieSession = require("cookie-session");
const cookieParser = require("cookie-parser");

var app = express();

const dev = process.env.NODE_ENV !== "production";
const nextApp = next({dev});
const port = process.env.PORT || config.get("port");
const handleRequest = nextApp.getRequestHandler();

nextApp.prepare().then(() => {
  require("./server/startup/cors")(app);
  require("./server/startup/db")();

  app.use(cookieParser("ilovescotchscotchyscotchscotch"));
  app.use(express.json());

  app.use(
    cookieSession({
      name: "MyAppName",
      keys: ["very secret key"],
      maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
    })
  );
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(flash());

  require("./server/services/passport")(passport);

  require("./server/startup/logging")();
  require("./server/startup/routes")(app);
  require("./server/startup/prod")(app);

  app.get("*", (req, res) => {
    return handleRequest(req, res);
  });
});

app.listen(port, () => console.log(`Listening at port ${port}`));

module.exports = app;

Here is my test file:

const request = require("supertest");

const {User} = require("./../../server/models/user");
const mongoose = require("mongoose");

let server;

beforeEach(() => {
  server = require("./../../server");
});
afterEach(async () => {
  await server.close();
});

describe("POST /api/signup", () => {
  it("should signin successfully", () => {});
});

This is my error:

TypeError: server.close is not a function

       9 | beforeEach(() => { server = require('./../../server'); });
      10 |   afterEach(async () => {    > 11 |     await server.close();
         |                  ^
      12 |
      13 |   });

what is happening here? Am I doing something fundamentally wrong here?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
sriram hegde
  • 2,301
  • 5
  • 29
  • 43
  • Does this answer your question? [how to properly close node-express server?](https://stackoverflow.com/questions/14515954/how-to-properly-close-node-express-server) – ggorlen Nov 22 '22 at 02:16

2 Answers2

13

In order to close the server, you must obtain the instance that is returned from the listen function. In your example, it appears that you call that function here:

app.listen(port, () => console.log(`Listening at port ${port}`));

So, you would need to get the instance returned and close that. E.g.

let appServer = app.listen(port, () => console.log(`Listening at port ${port}`));
...
appServer.close()
JBaczuk
  • 13,886
  • 10
  • 58
  • 86
7

At the end of your index.js, you want to export the listener, not app, so...

app.listen(port, () => console.log(`Listening at port ${port}`));
module.exports = app;

becomes...

const server = app.listen(port, () => console.log(`Listening at port ${port}`));
module.exports = server;

Should work from there.

aPaul
  • 219
  • 3
  • 9