前提:掌握Jest + Puppeteer
一 需要安装的插件
安装包 | 命令 |
---|---|
TypeScript | npm install typescript --save-dev |
Jest | npm install jest --save-dev |
ts-jest | npm install ts-jest --save-dev |
@types/jest | npm install @types/jest --save-dev |
二 安装步骤
1.mkdir UIAuto_Puppeteer //创建文件夹
2.cd UIAuto_Puppeteer // 进入该文件夹
3.安装以上包
4.tsc --init // 初始化相关配置文件,生成tsconfig.json
5.jest --init //初始化,生成jest.config.js
三 tsconfig.json配置
需要注意的是target 修改成es6,我们现在按照es6的语法特性
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"outDir": "dist",
}
}
四 jest配置
(一) 配置文件
- package.json : "scripts":{test": "jest"}
- jest.config.js : module_exports = {配置项}
(二) jest.config.js配置项解析
- roots :
当前目录 - testMatch : 设置识别哪些文件是测试文件(glob形式),与testRegex互斥,不能同时写
- moduleFileExtensions : 测试文件的类型
- transform : 用ts-jest 处理ts文件
module.exports = {
roots:[
"<rootDir>"
],
"moduleFileExtensions": [
"ts",
"js",
],
// 匹配__tests__文件夹下的后缀为 .test.ts文件
"testMatch": [
"**/__tests__/**/*.test.ts"
],
"transform": {
"^.+\\.ts$": "ts-jest"
}
};
五 文件目录
--UIAuto_Puppeteer
---__tests__
----demo
-----1.test.ts
-----2.test.ts
---node_mudules
---jest.config.js
---tsconfig.js
---package.json
---package-lock.json
$ UIAuto_Puppeteer : npm rum test
六 Puppeteer 配置
(一) 依赖的安装包
安装包 | 命令 |
---|---|
puppeteer | npm install puppeteer --save-dev |
解决Chromium无法下载 | npm i --save puppeteer --ignore-scripts |
解决Chromium无法下载 | set PUPPETEER_DOWNLOAD_HOST = https://storage.googleapis.com.cnpmjs.org |
@types/puppeteer | npm install @types/puppeteer --save-dev |
@types/jest-environment-puppeteer | npm install @types/puppeteer --save-dev |
@types/jest | npm install @types/jest --save-dev |
jest-puppeteer | npm install jest-puppeteer --save-dev |
jest-environment-puppeteer | npm install jest-environment-puppeteer --save-dev |
(二) 步骤
1.创建puppeteer_enviroment.js
2.配置jest.config.js,再jest.config.js里添加以下项,
- globalSetup:全部变量,再之前运行
- globalTeardown:全部变量,再之后运行
- testEnvironment:测试环境
"globalSetup": "jest-environment-puppeteer/setup",
"globalTeardown": "jest-environment-puppeteer/teardown",
"testEnvironment": "./puppeteer_enviroment.js",
4.配置puppeteer_enviroment.js
具体可以看看jest-environment-puppeteer的源码,这个代码很简单,setUp继承了jest-environment-puppetee,teardown() 继承了jest-environment-puppetee 里的teardown()
const PuppeteerEnviromenent = require('jest-environment-puppeteer');
class CustomEnvironmemnt extends PuppeteerEnviromenent {
async setup() {
await super.setup();
}
async teardown() {
await super.teardown()
}
}
module.exports = CustomEnvironmemnt
七 跑测试用例
代码如下,测试套件这边就不说了,比较简单
import { Page } from 'puppeteer';
describe('ly.com demo cases', () => {
let page: Page;
beforeEach(async () => {
page = await browser.newPage();
await page.goto('https://www.ly.com/');
});
afterEach(async ()=> {
await page.close();
})
test('test-ly-demo', async () => {
const logo = await page.$eval('.logo', el => el.getAttribute('title'));
console.log('logo');
await expect(logo).toEqual('同程旅游');
});
})