After writing all the endpoints I decided to add PORTS and JWT_key to .ENV by using dotenv package all work perfectly fine until I decided to do Integration testing now express.listen is not working and it automatically takes the port from .ENV file and I don't how
this is app.js
require("express-async-errors");
const Express = require("express");
const app= Express();
const winston = require("winston");
require("./start/logger")();
require("./start/routes")(express);
require("./start/db")();
require("./start/config")();
require("dotenv").config();
const port = process.env.PORT || 5000;
const server = app.listen(port, () =>
console.log(`listening on port ${port}`)
);
module.exports = server;
gets nothing on the console
this is .env file
PORT=9000
jwtPrivateKey="myPrivateKey"
as soon as I remove the port from .env file the server stop responding
this is my test file
const request = require("supertest");
let server;
describe("/api/genres", () => {
beforeEach(() => {
server = require("../../app");
});
afterEach(() => {
server.close();
});
describe("GET /", () => {
it("should return all genres", async () => {
jest.setTimeout(2000);
const res = await request(server).get("/api/genres");
expect(res.status).toBe(200);
});
});
});
please guide me through this I did not make a git repo for this otherwise I would have reset it
In your .env file change the variables from
port=9000
to
PORT=9000
You are getting the error because the variables inside of your .env are not in capital however in your code you're using process.env.PORT where they are in capitals.
Following on from what Heiko has said, it is good convention to use app instead of express. I would change the top of the code to:
const Express = require("express");
const app = Express();
And then change the express.listen() to:
const port = process.env.PORT || 5000;
app.listen(port, () =>
console.log(`listening on port ${port}`)
);
Thanks! I hope this helps.