目录
1 发布前检查的相关知识
1.1 持续集成的由来
持续集成最早是在客户端软件开发中提出的一种软件集成模式,有两个关键点:daily build和BVT(build verification test),BVT就是对build出的目标程序进行基本的验证测试
1.2 前端持续集成
前端项目的开发周期较短,一次build的时间通常也就几分钟,而测试工程师产生case的成本较高,并不太适用短周期的前端开发,前端工程师往往会采用更轻量级的测试方案,通常由3部分组成:
- Git hooks完成检查的时机
- 利用ESlint实现轻量级的代码语法检查
- 利用Phantomjs无头浏览器对最终的生产代码进行规则的检查和校验
2 Git hooks的基本用法
git像其它版本控制系统一样,能在特定的重要动作发生时触发自定义脚本,这些被触发的自定义脚本被称作Git hooks,它们存在于.git/hooks文件夹中。也就是说,git提供事件钩子,能被特定的事件触发后调用。Git hooks主要分2类,客户端hooks和服务端hooks。 客户端钩子pre-commit,pre-push等由诸如提交和合并这样的操作所调用,而服务器端钩子由诸如接收被推送的提交这样的联网操作所调用。注意在clone版本库时,客户端hooks是不会被clone下来的。git默认提供了一些用shell书写的.sample结尾的hooks模板,将.sample去掉便可被执行,也可使用其它脚本语言书写,指定执行环境即可。
在前端持续集成中,一般会将lint操作放进pre-commit钩子里,将check操作放进pre-push钩子里,下面是用js写的一个windows环境下的git hook示例
#!/bin/node
const process = require("process")
console.log("executing pre-commit")
process.exit(1)
类unix环境下则是
#!/usr/bin/env node
const process = require("process")
console.log("executing pre-commit")
process.exit(1)
3 ESlint的基本用法
ESlint是ECMAScript/JavaScript代码中识别和报告模式匹配的工具,也即检查语法错误的工具
3.1 ESlint安装和简单使用
- 使用 npm 安装 ESLint:
$ npm install eslint --save-dev
- 然后设置一个配置文件:
$ ./node_modules/.bin/eslint --init
- 之后,便可在任何文件或目录上运行ESLint如下:
$ ./node_modules/.bin/eslint yourfile.js
4 ESlint API
本节主要介绍如何在git hooks中应用ESlint,当ESlint检查出错误时,阻止git的提交,需要使用ESlint的Node API——ESlint class
在eslint-demo项目中初始化git,并在.git/hooks/目录下添加如下的pre-commit脚本
const { ESLint } = require("eslint"); // 此处的分号不能省略,因为下面有(
(async function main() {
// 1. Create an instance with the `fix` option.
const eslint = new ESLint({ fix: false }); // doesn't fix error
// 2. Lint files. This doesn't modify target files.
const results = await eslint.lintFiles(["index.js"]);
// 4. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 5. Output it.
console.log(resultText);
for(let result of results) {
if(result.errorCount > 0) {
process.exitCode = 1; // prohibit commit when there are errors
}
}
})().catch((error) => {
console.error(error);
});
此外,还需要应对一种特殊情况:git hooks中的ESlint只会对当前工作目录中的文件进行检查,如果当前工作目录中的文件存在语法错误,commit时ESlint会报错阻止提交。如果想将当前工作目录临时保存起来,恢复到此前提交到暂存区后的状态,可以利用git stash push -k
命令(k表示keep-index,保持暂存区,详见git stash),再执行commit。当提交完成后git会自动利用git stash pop
将工作区恢复到原来临时保存的状态,不过当commit的版本和git stash push -k
的版本有冲突时,会提交失败,需要手动解决冲突后再重新提交。
假设index.js中有如下代码已利用git add .
添加到index暂存区中
for(let i=0; i<3; i++) {
console.log(i)
}
let a = 1
如果增加一行let a=1
,再git add .
,然后执行git commit
,会因为不符合eslint规则而被阻止提交。
如果我们想将当前增加变量a的改动暂时缓存起来,将之前暂存到缓存区的版本提交,就可以使用git stash push -k
,然后执行git commit
,等提交完之后git会自动帮我们将之前stash的工作状态恢复
这步可以集成到pre-commit脚本中
#!/bin/node
const process = require("process")
console.log("executing pre-commit")
const { ESLint } = require("eslint")
const child_process = require("child_process")
async function exec(cmd) {
return new Promise((resolve)=>{
child_process.exec(cmd, resolve)
})
}
void async function main() {
// 1. Create an instance with the `fix` option.
const eslint = new ESLint({ fix: false }); // doesn't fix error
await exec("git stash -k push")
// 2. Lint files. This doesn't modify target files.
const results = await eslint.lintFiles(["index.js"]);
// await exec("git stash pop")
// 4. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 5. Output it.
console.log(resultText);
for(let result of results) {
if(result.errorCount > 0) {
process.exitCode = 1; // prohibit commit when there are errors
}
}
}().catch((error) => {
console.error(error);
});
5 使用无头浏览器检查DOM
5.1 目前自动化测试中检查DOM的几种方式
- 使用PhantomJS无头浏览器:已显得有些过时
- 使用Chrome-headless:谷歌推出的类似无头浏览器的chrome模式
- Puppeteer:由Chrome团队开发的Node库,提供了高层次的API来控制chrome-headless,可作为自动化测试库,也可用于截屏、创建pdf、页面间导航以及获取有关页面信息等功能
5.2 Puppeteer
- 安装
npm i puppeteer
默认会一并安装配套的Chrome浏览器npm i puppeteer-core
只单独安装puppeteer(需要配套兼容的Chrome)
- 简单使用
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
// console.log(await browser.version());
const page = await browser.newPage()
await page.goto("http://localhost:8080/main.html")
const a = await page.$("a") // $运行querySelector
console.log(await a.asElement().boxModel()) // 取盒模型
const imgs = await page.$$("img") // $$运行querySelectorAll
console.log(await imgs.length) // 打印DOM树中img的数量
browser.close();
})();
详细的使用方法可以参考puppeteer中文文档
- 将puppeteer入到Git hooks中,与eslint配合共同对commit和push前的项目进行代码语法检查和DOM检查
- 在客户端git hooks中使用eslint和puppeteer可以作为辅助工具
- 在服务端git hooks中使用eslint和puppeteer可以作为强制标准
客户端git hooks的pre-push脚本中集成puppeteer的示例代码
#!/bin/node
const process = require("process")
console.log("executing pre-push")
const child_process = require("child_process")
const puppeteer = require('puppeteer');
void async function main() {
const browser = await puppeteer.launch();
// console.log(await browser.version());
const page = await browser.newPage()
await page.goto("http://localhost:5000/main.html")
const ps = await page.$$("p") // $$run querySelectorAll
console.log(ps)
const pCounts = await page.$$eval("p", pArr => pArr.length)
if(pCounts !== 2) {// 检查dom中的p标签数量是否为1
process.exitCode = 1
}
browser.close();
}().catch((error) => {
console.error(error);
});
6 总结
本文介绍了前端工程化中持续集成(Continuous Integration)的相关知识,持续集成是源于客户端开发的一种集成模式,基本特点是"daily build"和"BVT(Build Verification Test)",但在前端邻域由于开发迭代周期短,测试工程师产生test case的成本较高,主要还是通过一些轻量化的测试工具进行自动测试,包括利用Git hooks在关键的git操作前执行测试脚本、使用ESlint对提交的代码进行语法检查以及利用自动化测试库Puppeteer对前端网页进行DOM检查,通过这些工具,我们可以对提交的项目代码进行基本的测试和质量把控,提高项目测试的质量和效率。
ps:如果觉得此文对你有帮助或启发,请不要吝惜你的点赞和分享,你的支持就是对我最大的鼓励。如有疑问,请留言或私信交流