Here is a solution for unit testing, as well as guidance on writing integration tests with supertest
server.js
:
const express = require('express');
const app = express();
app.get('/api/getUser', (req, res) => {
res.json({
email: req.email,
name: req.username,
});
});
server.test.js
:
const express = require('express');
jest.mock('express', () => {
const express = {
get: jest.fn(),
};
return jest.fn(() => express);
});
describe('60562419', () => {
it('should send json', () => {
const mApp = express();
const mReq = { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16736e777b667a7356717b777f7a3875797">[email protected]</a>', username: 'jest' };
const mRes = { json: jest.fn() };
mApp.get.mockImplementationOnce((route, handler) => {
handler(mReq, mRes);
});
require('./server');
expect(express).toBeCalled();
expect(mApp.get).toBeCalledWith('/api/getUser', expect.any(Function));
expect(mRes.json).toBeCalledWith({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6938e979b869a93b6919b979f9ad895999b">[email protected]</a>', name: 'jest' });
});
});
Results of the unit test showing 100% coverage:
PASS stackoverflow/60562419/server.test.js (9.939s)
60562419
✓ should send json (581ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
server.js | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.476s