Jest和Mocha是Node.js中主流测试框架,Jest开箱即用,适合前后端测试,内置断言、Mock和覆盖率工具;Mocha灵活需搭配Chai、Sinon等库,适合复杂项目。

在 Linux 环境下进行 Node.js 开发时,使用 Jest 或 Mocha 编写前后端测试用例是保证代码质量的重要环节。下面介绍如何针对前端和后端逻辑分别编写测试,并说明两种主流测试框架的基本用法。
Jest:全功能一体化测试框架
Jest 是 Facebook 推出的开箱即用测试工具,适合 React 前端和 Node.js 后端项目。它自带断言、Mock、覆盖率报告等功能。
1. 安装与初始化在项目根目录执行:
npm init -y npm install --save-dev jest
在 package.json 中添加运行脚本:
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
2. 编写后端单元测试(Node.js 示例)假设有一个简单的数学工具函数 math.js:
function add(a, b) {
return a + b;
}
module.exports = { add };
对应测试文件 math.test.js:
const { add } = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
3. 测试 Express 路由(后端接口)安装 supertest 模拟 HTTP 请求:
npm install --save-dev supertest
示例 Express 路由 app.js:
const express = require('express');
const app = express();
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello World' });
});
module.exports = app;
测试文件 app.test.js:
const request = require('supertest');
const app = require('./app');
test('GET /api/hello returns 200 and message', async () => {
const response = await request(app).get('/api/hello');
expect(response.statusCode).toBe(200);
expect(response.body.message).toBe('Hello World');
});
4. 前端组件测试(React + Jest)若使用 React,Jest 可配合 @testing-library/react 测试组件渲染和交互:
npm install --save-dev @testing-library/react @testing-library/jest-dom
测试一个按钮组件:
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';
test('calls onClick when button is clicked', () => {
const handleClick = jest.fn();
render();
fireEvent.click(screen.getByText('Click me'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
Mocha:灵活可扩展的测试框架
Mocha 更灵活,需要搭配断言库(如 Chai)和 Mock 工具(如 Sinon),适合复杂项目。
1. 安装 Mocha 与配套工具npm install --save-dev mocha chai sinon
修改 package.json 脚本:
"scripts": {
"test": "mocha"
}
2. 使用 Mocha + Chai 写测试测试同样的 math.js 文件:
const { expect } = require('chai');
const { add } = require('./math');
describe('Math Functions', () => {
it('should return 3 when adding 1 and 2', () => {
expect(add(1, 2)).to.equal(3);
});
});
3. 异步与 API 测试(Mocha + Supertest)测试 Express 接口:
const request = require('supertest');
const app = require('./app');
const { expect } = require('chai');
describe('GET /api/hello', () => {
it('should return hello message', async () => {
const res = await request(app).get('/api/hello');
expect(res.status).to.equal(200);
expect(res.body.message).to.equal('Hello World');
});
});
4. 前端测试中的 Mocha 使用场景Mocha 在前端中较少独立使用,通常被 Jest 或 Vitest 替代。但在某些需要自定义测试环境的项目中,可通过 mocha-webpack 配合浏览器环境运行测试。
最佳实践建议
- Node.js 新项目推荐使用 Jest,配置简单、速度快、覆盖全。
- 大型或已有项目若需高度定制,可选 Mocha 配合 Chai/Sinon。
- 前后端共用工具函数时,测试应放在公共模块并统一用 Node.js 运行。
- 确保 .gitignore 包含 node_modules 和测试生成的临时文件。
- 使用 --coverage 参数生成覆盖率报告,推动测试完善。









