In this article, we are going to discuss how we can write integration tests using Jest, Supertest and in process of writing integration tests, we often require mocking npm modules and dependencies, so we will also mock these npm modules and dependencies for smooth and complete testing.

Image for post

Photo by Abet Llacer from Pexels

Let’s get started, Jest is an excellent library probably one of the best to write tests, check test coverage, mock modules, and is equipped with a lot of other useful features. First, we will create a Node.js application on which we can write tests.

const express = require('express');
const app = express();
const PORT = process.env.PORT || 8000;
const jwt = require('jsonwebtoken');
const secretAccessKey = process.env.secretAccessKey || 'SecretAccessKey';

// To mock any NPM module make sure that you are not destructuring them while requiring them in your file.
// For example - If we use 
// const {verify} = require('jwt'); in place of const jwt = require();
// Jest would not be able to mock destructured modules. So, always keep in mind while writing your code to not to use destructured imports or require.

app.get('/verify-access-token', (req, res) => {
    const accessToken = req.headers['access-token'];
    try {
        jwt.verify(accessToken, secretAccessKey);
        return res.status(200).send({ message: 'Access token is verified' });
    } catch (err) {
        return res.status(401).send({ message: 'Unauthorized access' });
    }
});

app.listen(PORT, () => {
    console.log(`Server started at port ${PORT}`);
});

module.exports = app;

#tdd #jest #testing #javascript #programming

Write Integration Tests (and Mocks) with Jest and Supertest
14.60 GEEK