安装与使用

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-02-26

项目环境搭建

文档:testcafe 文档

初始化

  1. 创建目录,生成 package.json
npm init
# 交互输入
  1. 安装 testcafe 包
npm i -S testcafe

# 建议安装 ^1.9.5-rc.1 及以上版本
# 因为在 1.9.5 版本有一个bug 关于 await warning
  1. package.json 增加 test 脚本。
// package.json
{
  "script": {
    "test": "npm run test:phone",
    "test:pc": "testcafe chrome tests/ --skip-js-errors",
    "test:phone": "testcafe \"chrome:emulation:device=iphone X\" tests/ --skip-js-errors"
  }
}

参数解释:

  • chrome: 设置浏览器为 chrome,还可以为 firefox等,具体查看 Browsers
  • test/: 用来指定测试用例的目录为 test/
  • --skip-js-errors:该参数用来设置忽略js错误,避免因为js错误导致测试runner无法启动。
  • "chrome:emulation:device=iphone X": 指定为 chrome 开发工具下的移动端,机型为 iphone X,机型需要是 chrome 支持的,这里配置在 package.json 里面,所以需要用 \ 来转移双引号。

编写测试用例

示例: tests/index.ts

import { Selector } from 'testcafe';

fixture `Getting Started`
    .page `www.baidu.com`;

test('My first test', async t => {
    // Test code
});

执行 npm run test,则会打开一个 chrome 浏览器并跳转到 www.baidu.com

需要注意的是,import { Selector } from 'testcafe'; 这一行一定要有,因为一定要引入一次 testcafe,即使这里没有使用 Selector (用来选择页面元素的API),不然编译会报错 'fixture' is not defined and 'test' is not defined errors.

或者你使用了 eslint,则需要安装插件来避免此类错误提示。

npm i eslint --save-dev

npm install eslint-plugin-testcafe --save-dev

修改 .eslintrc.js

module.exports = {
  "plugins": [
    "testcafe"
  ],
  "extends": "plugin:testcafe/recommended"
}

testcafe 是支持 typescript 的,你可以在 testcafe 的配置文件 .testcaferc.json中配置 tsconfig.json的路径。

// .testcaferc.json
{
  "tsConfigPath": "/Users/s.johnson/testcafe/tsconfig.json"
}