用Mocha测试Node.js应用:单元测试与集成测试
引言
测试是确保Node.js应用质量的关键。Mocha是流行的测试框架,结合Chai断言库简化测试开发。本文将介绍如何用Mocha测试Node.js应用,涵盖单元测试和集成测试。
环境搭建
安装依赖:npm install mocha chai supertest --save-dev
单元测试
测试简单函数:
1 2 3 4 5 6 7 8 9 10 11 12
| module.exports.add = (a, b) => a + b;
const { expect } = require('chai'); const { add } = require('../math');
describe('Math', () => { it('should add two numbers', () => { expect(add(2, 3)).to.equal(5); }); });
|
运行:npx mocha
集成测试
测试Express API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const express = require('express'); const request = require('supertest'); const app = express();
app.get('/api/users', (req, res) => { res.json([{ id: 1, name: 'Alice' }]); });
describe('User API', () => { it('should return users', async () => { const res = await request(app).get('/api/users'); expect(res.status).to.equal(200); expect(res.body).to.have.lengthOf(1); expect(res.body[0]).to.have.property('name', 'Alice'); }); });
|
最佳实践
- 隔离测试:使用
beforeEach重置状态。
- 模拟依赖:使用
sinon模拟数据库或HTTP请求。
- 覆盖率:使用
nyc检查测试覆盖率。
总结
Mocha和Chai为Node.js提供了灵活的测试框架,适合单元测试和集成测试。通过合理的测试组织和依赖模拟,可以提升代码质量。希望本文的示例为你的测试开发提供指导!