lundi 23 mars 2020

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 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?

Aucun commentaire:

Enregistrer un commentaire