How to do API endpoint testing in Express JS using JEST?

There is an app with a several Express JS endpoints that are dependent on a MongoDB database ( Atlas to be more specific )

I’ve been struggling to figure out how to write appropriate integration tests with Jest testing framework.

First steps I want to accomplish:

  • To have an local testing database connection when the tests are run.
  • To start the application in test environment and wait for the database to successfully connect first before running the tests.

Current situation:

  1. App is being required from a module ( this executes the code and the app starts as like in normal development environment ).
  2. Tests takes place.
  3. Test results being outputted to the console.
  4. Information about whether database connection is succeeded or not follows up.

I assume that as per standard asynchronous behavior of NodeJS the tests are in some sort of racing condition with the database connection.

Would be awesome if someone could give me a hand understanding this environment switching from development to testing or any references to articles or any sort of information would be appreciated.

const request = require('supertest')
const app = require('../dist/app')

describe('Authentication API testing', () => {
    it('SHOULD RETURN Content-Type: application/json HEADER WITH Content-Length: 54 AND HTTP STATUS CODE 400 WHEN DOING POST /auth/register WITHOUT EMAIL ', () => {
        return request(app)
            .post('/auth/register')
            .send({ password: 'testPassword' })
            .expect('Content-Type', /json/)
            .expect('Content-Length', '54')
            .expect(400)
    })
})