Search code examples
javascriptmongodbexpressjestjssupertest

How to test with Jest after connecting to MongoDB?


I'm trying to set up testing for various routes in my Express server that require connectivity to my MongoDB database.

I'm not sure how to structure the Jest file in order to allow for testing. In my normal index.js file, I'm importing the app, and running app.listen within the connect .then call, like this:

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've tried running the same setup in my test.js files, but it's not working.

For 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);
    });

How is it possible to wait for a connection to MongoDB before running my tests?


Solution

  • So, turns out there were a few changes that I had to make. Firstly, I had to load in my .env file before running the tests. I did this by creating a jest.config.js file in the root of my project:

    module.exports = {
      verbose: true,
      setupFiles: ["dotenv/config"]
    };
    

    Then within the actual testing suite, I'm running beforeEach to connect to the MongoDB server.

    const connect = require("../dbs/mongodb/connect");
    const app = require("../app");
    const request = require("supertest");
    
    beforeEach(async() => {
      await connect();
    });
    
    describe("This is the test", () => {
      test("This should work", async done => {
        let res = await request(app).get("/home");
        expect(res.statusCode).toBe(200);
        done();
      })
    });