Skip to main content

Jest - Test & Mock

Works great for Node based or any api based projects.

Easy setup . Refer https://jestjs.io/docs/getting-started

Quick Setup - Steps

Step 1

npm install --save-dev jest
npm install --save-dev babel-jest @babel/core @babel/preset-env
npm install --save-dev axios # optional

Step 2

Make Babel Jest aware. Add babel.config.js.

module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

Step 3

Add jest.confi.js

/** @type {import('jest').Config} */
const config = {
verbose: true,
};

module.exports = config;

Package.json final state

  "devDependencies": {
"@babel/core": "^7.20.7",
"@babel/preset-env": "^7.20.2",
"axios": "^1.2.2",
"babel-jest": "^29.3.1",
"jest": "^29.3.1"
}

Adding Tests - Sample

Tests end with *.tests.js and can be located anywere. Sample test api.test.js

import { get, post } from './fetch-data';
import axios from 'axios';

beforeAll(async () => {
// Note: Expects Server to be running!
// Sign in, and store auth token
let creds = {
"username":"user1","password":"password1"
};
try {
const resp = await post('apisignin', creds);
if(resp.status != 200) throw "Auth error";
var authToken = resp.data.token;
// set common auth header
axios.defaults.headers.common['authorization'] = authToken;
} catch (e) {
throw "[ERROR] Expects Auth Server to be running"
}
});

describe('login with auth token', () => {
it('successfully access api url with auth token in header', async () => {
const resp = await get('apiwelcome');
expect(resp.data).toBe('Welcome user1!');
});
});

Http Util fetch-data.js

import axios from 'axios';

export const API_BASE = 'http://localhost:8000';

export const get = async (api, headers) => {
const url = `${API_BASE}/${api}`;
if(!headers) headers = {};
return await axios.get(url, { headers: headers});
};

export const post = async (api, payload, headers) => {
const url = `${API_BASE}/${api}`;
if(!headers) headers = {};
headers['content-type'] = 'application/json'; // always set to json
return await axios.post(url, payload, headers);
};