在 Jest 中,describe、test 和 it 都是用于组织测试代码的函数:
describe 函数:
- 用于将相关的测试用例分组,形成测试套件(Test Suite)
- 接受两个参数:描述字符串和回调函数
- 可以嵌套使用,形成层级结构
- 示例:
describe('User module', () => { ... })
test 函数:
- 定义一个单独的测试用例
- 是
it函数的别名,两者功能完全相同 - 接受两个参数:描述字符串和测试函数
- 示例:
test('should return user name', () => { ... })
it 函数:
- 与
test功能完全相同,是test的别名 - 使用
it可以让测试代码读起来更像自然语言 - 示例:
it('should return user name', () => { ... })
使用示例:
javascriptdescribe('Calculator', () => { describe('addition', () => { test('should add two positive numbers', () => { expect(add(2, 3)).toBe(5); }); it('should handle negative numbers', () => { expect(add(-2, 3)).toBe(1); }); }); });
最佳实践:
- 使用
describe对相关测试进行逻辑分组 - 测试描述应该清晰表达测试意图
- 保持每个测试用例的单一职责