I'm trying to test Nodejs and Express API using JEST and Supertest everytime I run npm test Jest fails with an error You are trying to import a file after the Jest environment has been torn down I expect the test to run and send API requests to check if all APIs are working as expected.
Here is my server.js file structure
const express = require("express");
const { readdirSync } = require("fs");
const cors = require("cors");
const morgan = require("morgan");
const dotenv = require("dotenv");
const connectDB = require("./config/DB");
const { erroHandler } = require("./middlewares/errorHandler");
//Load Config
dotenv.config({ path: "./config/config.env" });
//db connecnt
connectDB();
// Jest testing
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan("dev"));
app.use(cors());
readdirSync("./routes").map((r) => app.use("/api", require("./routes/" + r)));
app.use(erroHandler);
module.exports = app;
I'm trying to run app.listen() in another file which I call index.js
const app = require("./server");
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
console.log(`Server Listening ${PORT}`);
});
In my test file, first I'm trying to connect to the Database, then start testing the API.
const app = require("../server");
const supertest = require("supertest");
beforeEach(() => {
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
console.log(`MongoDB connected`);
} catch (error) {
console.log("Mongoose Erro", error);
process.exit(1);
}
};
});
it("Testing to see if Jest works", () => {});
In my backage.json file npm test should run JEST
"scripts": {
"test": "jest",
},
Here is the complete problem, if you get better suggestions is also welcomed.