Backstop.js 视觉回归测试
Backstop.js 视觉回归测试
Backstop.js
Backstop.js 是一个开源工具,旨在自动化视觉回归测试。它通过截取网页的屏幕截图并与基准图片进行像素级比较,检测 UI 的变化。
与手动检查或依赖设计师的肉眼不同,Backstop.js 提供了一种可重复、可量化的方式来验证视觉一致性。无论是 CSS 调整、JavaScript 动态渲染,还是第三方库更新,它都能捕捉到潜在的视觉问题。
快速上手 Backstop.js
通过一个简单的例子,看看如何在项目中集成 Backstop.js。
安装
1
2
3
npm install -g backstopjs
# 或者本地安装
npm install --save-dev backstopjs
初始化项目
在项目根目录运行:
1
backstop init
这会生成一个 backstop.json
配置文件,包含默认的测试场景。
配置测试场景
编辑 backstop.json
,定义要测试的页面和视口。例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
"id": "my_project",
"viewports": [
{ "label": "desktop", "width": 1440, "height": 900 },
{ "label": "mobile", "width": 375, "height": 667 }
],
"scenarios": [
{
"label": "Homepage",
"url": "http://localhost:3000/",
"referenceUrl": "http://localhost:3000/", // 基准 URL
"delay": 500 // 等待渲染完成
}
],
"paths": {
"bitmaps_reference": "backstop_data/bitmaps_reference",
"bitmaps_test": "backstop_data/bitmaps_test",
"html_report": "backstop_data/html_report"
},
"engine": "puppeteer",
"report": ["browser"],
"engineOptions": {
"args": ["--no-sandbox"]
}
}
生成基准图片
运行以下命令,生成初始的参考截图:
1
backstop reference
执行测试
代码改动后,运行测试并比较差异:
1
backstop test
Backstop.js 会生成一个 HTML 报告,展示差异区域(如果有)。
高级用法
- 动态内容处理
对于包含动态数据的页面,可以用onBeforeScript
或onReadyScript
自定义脚本。例如,模拟登录状态:1 2 3 4 5 6 7
"scenarios": [ { "label": "Dashboard", "url": "http://localhost:3000/dashboard", "onReadyScript": "login.js" } ]
在
login.js
中:1 2 3 4 5
module.exports = async (page, scenario) => { await page.type('#username', 'testuser'); await page.type('#password', 'password'); await page.click('#login-btn'); };
- CI/CD 集成
将 Backstop.js 加入 GitHub Actions 或 Jenkins:1 2 3 4 5 6 7 8 9 10 11
# .github/workflows/test.yml name: Visual Regression Test on: [push] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - run: npm install - run: npm run start & # 启动本地服务 - run: npx backstop test
- 容差设置
如果某些微小差异可以接受,调整misMatchThreshold
(默认 0.1%):1 2 3 4 5 6 7
"scenarios": [ { "label": "Homepage", "url": "http://localhost:3000/", "misMatchThreshold": 0.5 } ]
This post is licensed under CC BY 4.0 by the author.