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

在 Linux 环境下进行 Node.js 开发时,使用 Jest 或 Mocha 编写前后端测试用例是保证代码质量的重要环节。下面介绍如何针对前端和后端逻辑分别编写测试,并说明两种主流测试框架的基本用法。
Jest 是 Facebook 推出的开箱即用测试工具,适合 React 前端和 Node.js 后端项目。它自带断言、Mock、覆盖率报告等功能。
1. 安装与初始化在项目根目录执行:
npm init -y npm install --save-dev jest
在 package.json 中添加运行脚本:
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}假设有一个简单的数学工具函数 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);
});安装 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');
});若使用 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(<Button onClick={handleClick} />);
fireEvent.click(screen.getByText('Click me'));
expect(handleClick).toHaveBeenCalledTimes(1);
});Mocha 更灵活,需要搭配断言库(如 Chai)和 Mock 工具(如 Sinon),适合复杂项目。
1. 安装 Mocha 与配套工具npm install --save-dev mocha chai sinon
修改 package.json 脚本:
"scripts": {
"test": "mocha"
}测试同样的 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);
});
});测试 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');
});
});Mocha 在前端中较少独立使用,通常被 Jest 或 Vitest 替代。但在某些需要自定义测试环境的项目中,可通过 mocha-webpack 配合浏览器环境运行测试。
以上就是Linux 开发:如何用 Jest / Mocha 编写前后端测试用例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号