devamat
devamat

Reputation: 2503

Jest: Testing issue with process.env.PORT

EDIT: after playing around a little I realized that the issue is not related to the process variables, but to the fact that my server instance is executed only once for some reason. I'm still looking into it, I'll keep the post updated.

I am trying to get 100% coverage, but I'm stuck at testing this line:

const port = config.get("port") || process.env.PORT || 3000;

It seems that I can't set process.env.PORT more than once.

const config = require("config");

// This checks if a port is being used
function portUsed(port) {
  return new Promise((resolve, reject) => {
    const net = require("net");
    const server = net.createServer();

    server.once("error", err => {
      if (err.code === "EADDRINUSE") {
        resolve(true);
      }
    });

    server.once("listening", () => {
      server.close();
      resolve(false);
    });

    server.listen(port);
  });
}

describe("index", () => {
  // this works
  it("should use process.env.PORT if config.get('port') is not set", async () => {
    config.port = null;
    process.env.PORT = 3333;
    const server = require("../../index");
    const result = await portUsed(3333);
    expect(result).toBe(true);
    await server.close();
  });

  // This does not work, but if you comment out / remove the previous test, it will work!
  it("should default to port 3000 if other variables are not set", async () => {
    config.port = null;
    delete process.env.PORT;
    const server = require("../../index");
    const result = await portUsed(3000);
    expect(result).toBe(true);
    await server.close();
  });

});

Basically only one of those two tests will run. What am I doing wrong?

index.js

const express = require("express");
const app = express();
const config = require("config");

const logger = require("./startup/logging");
require("./startup/console")(app);
require("./startup/database")();
require("./startup/routes")(app);

app.use(express.urlencoded({ extended: true }));

logger.info(config.get("name"));
// delete config.port;
// delete process.env.PORT;
// console.log("config", config.port);
console.log("server", process.env.PORT);
const port = config.get("port") || process.env.PORT || 3000;
const server = app.listen(port, () => logger.info(`Listening on port ${port}.`));

module.exports = server;

Upvotes: 0

Views: 575

Answers (1)

devamat
devamat

Reputation: 2503

The reason why my test were not working is because the modules required (require("../../index.js")) will be cached, hence only one instance of the server is created. To solve this just use:

beforeEach(() => jest.resetModules());

Upvotes: 1

Related Questions