Testing your express web app - Hives/makers-weather-station GitHub Wiki

Jest has no built in capability to test express web framework. You need to install the following packages namely, supertest to return the request.

npm install --save-dev babel-cli babel-preset-env jest supertest superagent

Seperate your app.js with a server.js for setting up port config in then require the app.js in the server.

app.js:

const express = require('express')
const app = express()
app.get('/', (req, res) => {
    res.status(200).send('Hello World!')
})
module.exports = app

server.js:

const app = require('./app');

app.listen(3000, () => {
  console.log('App listening on port 3000!');
});

Now for testing: there are many ways to do it, using done/promise/async await/supertest etcetc See : Jest testing with supertest

We used async way for testing:

const request = require('supertest');
const app = require('../app.js');

describe('Test the root path', () => {
  test('It should response the GET method', async () => {
    const response = await request(app).get('/');
    expect(response.statusCode).toBe(200);
  });
});

Database connection testing with mongodb:

Test: Notice before all tests do mongo connect then when "done" dc from database

describe('Test the addLike method', () => {
    beforeAll(() => {
        mongoDB.connect();
    });
    afterAll((done) => {
        mongoDB.disconnect(done);
    });
}