JavaScript Mocha框架
外观
JavaScript Mocha框架[编辑 | 编辑源代码]
Mocha 是一个功能丰富的 JavaScript 测试框架,运行在 Node.js 和浏览器环境中,用于异步测试和同步测试。它提供了灵活的报告、断言库集成(如 Chai)和钩子函数(如 `beforeEach`、`afterEach`),适合单元测试、集成测试和行为驱动开发(BDD)。
概述[编辑 | 编辑源代码]
Mocha 的主要特点包括:
- 支持同步和异步测试(使用 `done` 回调或返回 Promise)。
- 提供多种接口(如 `describe`/`it` 风格的 BDD 接口)。
- 可扩展的报告功能(支持多种格式,如 spec、dot、TAP)。
- 兼容多种断言库(如 Node.js 自带的 `assert`、Chai、Should.js)。
安装与基本用法[编辑 | 编辑源代码]
安装[编辑 | 编辑源代码]
通过 npm 安装 Mocha:
npm install --save-dev mocha
基本测试结构[编辑 | 编辑源代码]
Mocha 使用 `describe` 定义测试套件,`it` 定义测试用例:
const assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.strictEqual([1, 2, 3].indexOf(4), -1);
});
});
});
运行测试:
npx mocha
输出示例:
Array #indexOf() ✓ should return -1 when the value is not present 1 passing (5ms)
异步测试[编辑 | 编辑源代码]
Mocha 支持异步测试,可通过 `done` 回调或返回 Promise:
describe('Async Test', function() {
it('should complete after 1 second', function(done) {
setTimeout(() => {
assert.ok(true);
done();
}, 1000);
});
it('should resolve a promise', function() {
return Promise.resolve('success').then(result => {
assert.strictEqual(result, 'success');
});
});
});
钩子函数[编辑 | 编辑源代码]
Mocha 提供生命周期钩子:
- `before()`:在所有测试前运行一次。
- `after()`:在所有测试后运行一次。
- `beforeEach()`:在每个测试前运行。
- `afterEach()`:在每个测试后运行。
示例:
describe('Hooks', function() {
let counter = 0;
before(() => {
counter = 10;
});
beforeEach(() => {
counter++;
});
it('should increment counter', function() {
assert.strictEqual(counter, 11);
});
it('should increment again', function() {
assert.strictEqual(counter, 12);
});
});
断言库集成[编辑 | 编辑源代码]
Mocha 不内置断言库,但可与 Chai 等库结合使用:
const { expect } = require('chai');
describe('Chai Assertions', function() {
it('should use expect style', function() {
expect([1, 2, 3]).to.have.lengthOf(3);
});
});
实际案例[编辑 | 编辑源代码]
测试一个简单函数[编辑 | 编辑源代码]
假设有一个计算阶乘的函数:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
describe('Factorial', function() {
it('should return 1 for 0', function() {
assert.strictEqual(factorial(0), 1);
});
it('should return 120 for 5', function() {
assert.strictEqual(factorial(5), 120);
});
});
测试 API 请求[编辑 | 编辑源代码]
使用 `axios` 测试异步 API:
const axios = require('axios');
describe('API Test', function() {
it('should fetch user data', async function() {
const response = await axios.get('https://api.example.com/users/1');
assert.strictEqual(response.status, 200);
assert.strictEqual(response.data.name, 'John Doe');
});
});
高级配置[编辑 | 编辑源代码]
配置文件[编辑 | 编辑源代码]
创建 `.mocharc.js` 文件自定义配置:
module.exports = {
timeout: 5000,
reporter: 'dot',
require: ['@babel/register']
};
测试覆盖率[编辑 | 编辑源代码]
结合 `nyc` 计算覆盖率:
npm install --save-dev nyc
npx nyc mocha
总结[编辑 | 编辑源代码]
Mocha 是一个灵活且强大的测试框架,适合从简单到复杂的测试场景。通过结合断言库和生命周期钩子,可以构建可维护的测试套件。