Вот решение для модульного тестирования, кроме того, вы можете написать интеграционный тест, используя 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: 'example@gmail.com', 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: 'example@gmail.com', name: 'jest' });
});
});
Результаты модульных испытаний со 100% покрытием:
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