Test Cafe 作为一款测试框架,非常适合开展 UI 自动化测试、浏览器兼容性测试,同时支持 TypeScript. 本文介绍 使用 Test Cafe 进行 UI 自动化的实例。 安装 Test Cafe 在自己电脑上新建一个文件夹,比如叫 demo,首先在这个目录下使用 npm init 创建 package.json: npm init 一路按回车之后,生成 package.json ,然后再执行 npm install ---save-dev testcafe 安装 testcafe ,并且自动更新 package.json ,结果大致如下这样: { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "testcafe": "^1.6.1" } } 这里的 scripts.test 是执行测试的命令,我们 编写完测试脚本 后要修改为可以运行的格式。 编写测试用例 经过 上节 安装以后,就可以编写测试脚本了。我们编写一个在baidu上搜索内容的动作。 新建一个名为 test 的文件夹,在其中新建一个 baidu.test.ts 文件: $ mkdir -p test && cd test && touch baidu.test.ts 文件名中加上 .test. 的目的是方便过滤出测试脚本。编辑 baidu.test.ts,填入内容: import { Selector } from 'testcafe'; fixture ('baidu试验') .page ('https://www.baidu.com'); test ('baidu搜索关键字', async t => { await t .typeText(Selector('#kw'),"lfhacks.com") .click(Selector('#su')); }); 保存即可,然后按 下节 介绍的方法执行。脚本中的 fixture、test 的含义见 前端测试工具 TestCafe 测试代码结构 一文, Selector 的含义见 前端测试工具 TestCafe 中的 Selector 中有介绍。 执行测试用例 按照 上节 的方法编辑好测试脚本后,去修改 安装一节 中所讲的 package.json 中的 scripts.test : { …… "scripts": { "test": "testcafe chrome test/*.test.ts" }, …… } 保存后就可以利用 npm 执行测试用例了。 $ npm test 执行后,会自动出现浏览器的窗口,但是有可能中途退出,原因可能是 baidu 页面出现了 js 错误。 忽略页面错误 如果页面出错,测试会终止,并且报下面的错: 按报错信息中的提示,我们可以使用 --skip-js-errors 开关忽略 js 错误。修改 package.json 中的 scripts.test : { …… "scripts": { "test": "testcafe chrome test/*.test.ts --skip-js-errors" }, …… } 保存后再执行 npm test 就能顺利执行。 放慢测试速度 默认执行速度非常快,为了能看清楚,可以设置执行测试的速度。修改脚本如下: import { Selector } from 'testcafe'; fixture ('baidu试验') .page ('https://www.baidu.com') .beforeEach(async t => { await t.setTestSpeed(0.5); }); test ('baidu搜索关键字', async t=>{ await t .typeText(Selector('#kw'),"lfhacks.com") .click(Selector('#su')); }); setTestSpeed的参数值,位于 0.01(最慢)到 1(最快)之间。修改后的效果如下: 更换浏览器 更换其他浏览器,只需要修改命令行参数即可,十分方便: 使用 FireFox: { …… "scripts": { "test": "testcafe firefox test/*.test.ts" }, …… } 使用 无界面 headless Chrome: …… "scripts": { "test": "testcafe chrome:headless test/*.test.ts" }, …… } headless 浏览器在 另一篇文章 中给还有详细介绍。 使用其他设备上的浏览器 在 这篇文章 提过,Test cafe 提供了服务端的结构,所以除了 使用本地浏览器 以外,还可以使用其他设备上的浏览器,只要相互之间有网络相联通。 修改 package.json : { …… "scripts": { "test": "testcafe remote test/*.test.ts" }, …… } 保存后执行 npm test 就在本地起了一个测试服务,并在控制台上显示了一个URL,等待其他浏览器访问。 使用其他电脑浏览器,打开这个 URL,就能看到自动测试的过程。非常适合兼容性测试,比如服务起在 Linux 服务器,而使用 windows 端的 IE 访问。 如果使用移动端的浏览器,TestCafe 还提供了 --qr-code 参数,用来在命令行上显示二维码,方便移动端扫码得到测试 URL. Node API npm 上由许多参数开关,比如 上节 提到的 --qr-code 参数。如果参数过多,不希望从 npm 入口执行测试,可以直接从 Node 直接执行,在代码中配置参数。具体做法是:编写 index.js ,填入内容: const createTestCafe = require('testcafe'); let testcafe = null; createTestCafe('localhost', 1337, 1338) .then(tc => { testcafe = tc; const runner = testcafe.createRunner(); return runner .src('tests/fixture1.js') .browsers(['chrome', 'safari']) .reporter('minimal') .run({ skipJsErrors: true }); }) .then(failedCount => { console.log('Tests failed: ' + failedCount); testcafe.close(); }); (未完待续)