1 回答
TA贡献1789条经验 获得超10个赞
单元测试解决方案:
route.js:
const express = require('express');
const router = express.Router();
router.get('', (req, res, next) => {
try {
res.status(200).render('../views/');
} catch (error) {
next(error);
}
});
router.get('*', (req, res, next) => {
try {
res.status(404).render('../views/not-found');
} catch (error) {
next(error);
}
});
module.exports = router;
route.test.js:
describe('64051580', () => {
afterEach(() => {
jest.resetModules();
jest.restoreAllMocks();
});
it('should render views', () => {
const express = require('express');
const mRouter = { get: jest.fn() };
jest.spyOn(express, 'Router').mockImplementationOnce(() => mRouter);
const mReq = {};
const mRes = { status: jest.fn().mockReturnThis(), render: jest.fn() };
const mNext = jest.fn();
mRouter.get.mockImplementation((path, callback) => {
if (path === '') {
callback(mReq, mRes, mNext);
}
});
require('./route');
expect(mRes.status).toBeCalledWith(200);
expect(mRes.render).toBeCalledWith('../views/');
});
it('should handle error', () => {
const express = require('express');
const mRouter = { get: jest.fn() };
jest.spyOn(express, 'Router').mockImplementationOnce(() => mRouter);
const mReq = {};
const mErr = new Error('parse');
const mRes = {
status: jest.fn().mockReturnThis(),
render: jest.fn().mockImplementationOnce(() => {
throw mErr;
}),
};
const mNext = jest.fn();
mRouter.get.mockImplementation((path, callback) => {
if (path === '') {
callback(mReq, mRes, mNext);
}
});
require('./route');
expect(mNext).toBeCalledWith(mErr);
});
it('should render 404 not found view', () => {
const express = require('express');
const mRouter = { get: jest.fn() };
jest.spyOn(express, 'Router').mockImplementationOnce(() => mRouter);
const mReq = {};
const mRes = { status: jest.fn().mockReturnThis(), render: jest.fn() };
const mNext = jest.fn();
mRouter.get.mockImplementation((path, callback) => {
if (path === '*') {
callback(mReq, mRes, mNext);
}
});
require('./route');
expect(mRes.status).toBeCalledWith(404);
expect(mRes.render).toBeCalledWith('../views/not-found');
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/64051580/route.test.js
64051580
✓ should render views (656ms)
✓ should handle error (17ms)
✓ should render 404 not found view (16ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 90.91 | 100 | 100 | 90.91 | |
route.js | 90.91 | 100 | 100 | 90.91 | 16 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 4.28s, estimated 10s
添加回答
举报