JavaScript (Node.js) 测试:框架与工具
测试是开发可靠软件不可或缺的一部分。在 Node.js 生态系统中,有许多用于测试自动化的工具,从简单的 assert 库到强大的框架。在本文中,我们将介绍主要的框架和工具,帮助您为 Node.js 应用程序编写高质量的测试。
为什么测试 Node.js 应用程序很重要?
Node.js 常用于服务器端开发、API 和微服务。此类系统中的错误可能导致代价高昂的停机或数据泄露。自动化测试可以:
- 在重构时快速发现回归问题
- 记录代码的行为
- 确保与数据库和外部服务集成时的稳定性
- 通过可验证的场景加速代码审查
Node.js 中的主要测试类型
- 单元测试 — 单独测试单个函数或模块。
- 集成测试 — 测试多个模块之间的交互(例如,与数据库或 API)。
- 端到端测试 — 通过浏览器或 HTTP 请求模拟用户操作。
Jest — 来自 Facebook 的通用框架
Jest 是最流行的 JavaScript 测试框架。它包含所有必需的功能:测试运行器、断言库、模拟以及内置的异步支持。
// math.jsfunction add(a, b) { return a + b;}module.exports = { add };
// math.test.jsconst { add } = require('./math');
test('adds 1 + 2 to equal 3', () => { expect(add(1, 2)).toBe(3);});Jest 支持:
- 自动发现测试文件 (
*.test.js) - 内置的模拟和间谍功能
- 通过
--coverage标志实现代码覆盖率 - 通过
async/await处理异步代码
Mocha + Chai — 灵活的经典组合
Mocha 是一个测试运行器,为测试提供结构(describe, it)。断言通常使用 Chai 库,它提供多种风格(assert, expect, should)。
const chai = require('chai');const expect = chai.expect;const { add } = require('./math');
describe('Math operations', () => { it('should add two numbers', () => { expect(add(2, 3)).to.equal(5); });});Mocha 常与以下工具结合使用:
- Chai — 用于可读的断言
- Sinon — 用于模拟、桩和间谍
- Supertest — 用于测试 HTTP 服务器
Sinon — 强大的模拟和间谍功能
Sinon.JS 是一个用于创建测试替身的库。它允许将测试代码与外部依赖项隔离。
const sinon = require('sinon');const { expect } = require('chai');
const userService = { getUser: (id) => { /* 外部调用 */ }};
describe('User controller', () => { it('should call getUser with correct id', () => { const spy = sinon.spy(userService, 'getUser'); userService.getUser(123); expect(spy.calledWith(123)).to.be.true; spy.restore(); });});Supertest — 测试 HTTP 服务器
Supertest 允许在不启动真实端口的情况下测试 Express/Koa 服务器。它模拟 HTTP 请求并检查响应。
const request = require('supertest');const express = require('express');
const app = express();app.get('/hello', (req, res) => { res.status(200).json({ message: 'Hello World' });});
describe('GET /hello', () => { it('responds with json', (done) => { request(app) .get('/hello') .expect('Content-Type', /j