I am currently in the process of setting up testing for various routes within my Express server that rely on connectivity to my MongoDB database.
I am facing a challenge in structuring the Jest file to enable seamless testing. In my regular index.js file, I import the app and execute app.listen
within the connect .then
call, as shown below:
const connect = require("../dbs/mongodb/connect");
connect()
.then(_ => {
app.listen(process.env.PORT, _ => logger.info('this is running')
})
.catch(_ => logger.error('The app could not connect.');
I attempted to replicate the same setup in my test.js files, but it did not yield the desired results.
Here is an example:
const connect = require("../dbs/mongodb/connect");
const request = require("supertest");
const runTests = () => {
describe("Test the home page", () => {
test("It should give a 200 response.", async () => {
let res = await request(app).get("/");
expect(res.statusCode).toBe(200);
});
});
};
connect()
.then(_ => app.listen(process.env.PORT))
.then(runTests)
.catch(err => {
console.error(`Could not connect to mongodb`, err);
});
Is there a way to ensure a connection to MongoDB is established before executing my tests?