1.单元测试
写一段代码测试一段代码的 样式 功能 组件 等
单元测试:是指对软件中的最小可测试单元进行检查和验证
前端单元测试的意义
- 检测出潜在的bug
- 快速反馈功能输出,验证代码是否达到预期
- 保证代码重构的安全性
- 方便协作开发
单元测试代码
// 被测试对象;为程序最小组成单元;可以是 function 方法集合Method 类 等等
let add = (a, b) => a + b;
let subtraction = (a, b) => a - b;
// 测试代码
let expect = (res) => {// 调用方法res返回值
return {
toBe: (actual) => {//actual 预期值
if (res !== actual) {
throw new Error("预期值与实际值不符")// 方法抛出错误
}
}
}
}
expect(add(1, 2)).toBe(3);
let test = (desc, fn) => {//desc描述,fn方法
try { //判断方法是否可执行
fn();
} catch(e) {
console.log(`${desc}没有通过`)
}
}
test('加法测试', () => {
expect(add(1, 2)).toBe(3);
})
Jest的基础使用
Jest:是Facebook的一套JavaScript的测试框架(几乎集成了所有的测试所需,对react特别友好)
0.安装jest
- 创建被测试对象math.js
- 创建test文件math.test.js
- 修改package.json文件
- 执行npm run test
Jest的安装
- 安装Node
- npm i -D jest 或yarn add -D jest 进行安装( 淘宝镜像npm i -D jest --registry https://registry.npm.taobao.org)
- 通过npm ls jest 查看是否安装成功