1.单元测试是什么?
单元: 代码模块(函数、对象、类、模块);
测试:自动化测试替代手动测试(QA).
优点:
1.验证代码正确性
2.保证重构正确性
3.快速反馈
4.简化集成过程
5.最好的开发文档 2.如何测试一个单元?
AAA模式
| Arrange | Act | Assert |
|---|---|---|
| Test input | Function 单元测试 | Test Failed/Passed |
断言代码格式:
expect(result).matcher(expected)
例如:test("should return true when actual value equals expected value", ()=>{
const actualValue = 2;
const expectedValue = 2;
const result = expectedValue = actualValue;
const expectedResult = true;
expect(reslut).toEqual(expected);});
matcher匹配器:
1、toBe 严格相等,值引用 Object.is()
2、toEqual 值相等
3、toBeNull
4、toBeUndefined
5、toBeDefined
6、toBeTruthy
7、toBeFalsy
// 数字
8、toBeGreaterThan 大于
9、toBeGreaterThanOrEqual 大于等于
10、toBeLessThan 小于
11、toBeLessThanOrEqual 小于等于
// 字符串
12、toMatch 匹配 (可以是字符串,可以是正则)
// 数组
13、toContain 是否包含
// 异常
14、toThrow 异常匹配器
15、not 不是
3.测试工具
Jest、Jasmine、AVA、MOCHA
特点:
1.零配置
2.优秀的API支持
3.轻松的Mock
4.快速且安全
5.自动生成代码覆盖率报告