Package Exports
- foliko
- foliko/src/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (foliko) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
JavaScript 测试代码示例
这个项目展示了现代 JavaScript 测试的最佳实践,使用 Jest 作为测试框架。
文件结构
test-example.js- 完整的测试示例,包含多种测试类型simple-test-example.js- 简洁的测试示例,适合初学者package.json- 项目配置和 Jest 设置
包含的测试类型
1. 单元测试
- 函数测试
- 类方法测试
- 边界情况测试
- 异常测试
2. 异步测试
- Promise 测试
- async/await 测试
- 超时处理
3. 集成测试
- 多个类的组合测试
- 完整流程测试
4. Mock 和 Spy
- 模拟函数
- 模拟 API 调用
- 验证函数调用
5. 参数化测试
- 使用
test.each测试多组数据
6. 快照测试
- 对象结构验证
最佳实践展示
1. AAA 模式 (Arrange-Act-Assert)
test('应该正确计算两个数的和', () => {
// Arrange: 准备测试数据
const a = 5;
const b = 3;
const expected = 8;
// Act: 执行被测试的方法
const result = calculator.add(a, b);
// Assert: 验证结果
expect(result).toBe(expected);
});2. 描述性测试名称
- 使用 "should" 描述预期行为
- 包含测试条件
- 清晰表达测试目的
3. 测试隔离
- 每个测试独立运行
- 使用
beforeEach重置状态 - 避免测试间的依赖
4. 恰当的断言
- 使用合适的匹配器
- 验证异常
- 检查异步结果
5. 测试覆盖率
- 行覆盖率
- 分支覆盖率
- 函数覆盖率
- 语句覆盖率
安装和运行
1. 安装依赖
npm install2. 运行测试
# 运行所有测试
npm test
# 监视模式(文件变化时自动运行)
npm run test:watch
# 生成覆盖率报告
npm run test:coverage
# 详细输出
npm run test:verbose
# 更新快照
npm run test:update3. 查看覆盖率报告
运行 npm run test:coverage 后,打开 coverage/index.html 查看详细的覆盖率报告。
Jest 配置说明
在 package.json 中的 Jest 配置:
{
"jest": {
"testEnvironment": "node", // 测试环境
"verbose": true, // 详细输出
"collectCoverage": true, // 收集覆盖率
"coverageDirectory": "coverage", // 覆盖率输出目录
"coverageReporters": ["text", "lcov", "html"], // 报告格式
"coverageThreshold": { // 覆盖率阈值
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
},
"testMatch": [ // 测试文件匹配模式
"**/__tests__/**/*.js",
"**/?(*.)+(spec|test).js"
],
"testTimeout": 10000, // 测试超时时间
"clearMocks": true, // 自动清理 mock
"resetMocks": true, // 重置 mock
"restoreMocks": true // 恢复原始实现
}
}测试技巧
1. 测试异步代码
// 使用 async/await
test('应该异步返回数据', async () => {
const result = await fetchData();
expect(result).toEqual({ data: '测试数据' });
});
// 测试异步异常
test('应该抛出异步错误', async () => {
await expect(asyncFunction()).rejects.toThrow('错误信息');
});2. Mock 函数
// 创建 mock 函数
const mockFn = jest.fn();
// 设置返回值
mockFn.mockReturnValue('返回值');
// 验证调用
expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn).toHaveBeenCalledWith('参数');3. 参数化测试
test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('add(%i, %i) should equal %i', (a, b, expected) => {
expect(a + b).toBe(expected);
});4. 快照测试
test('对象应该匹配快照', () => {
const obj = {
id: 1,
name: '测试',
date: new Date('2024-01-01')
};
expect(obj).toMatchSnapshot({
date: expect.any(Date) // 忽略具体日期值
});
});常见问题
1. 测试运行太慢
- 减少不必要的异步等待
- 使用
jest.useFakeTimers()模拟时间 - 避免在测试中执行真实 API 调用
2. 测试不稳定(Flaky Tests)
- 确保测试独立
- 避免依赖外部状态
- 使用固定的测试数据
3. 覆盖率不足
- 添加边界情况测试
- 测试错误处理路径
- 验证所有分支条件
扩展阅读
许可证
MIT