Eson Wong's Blog

生活随想、学习笔记、读书总结、创作记录

0%

Playwright E2E 测试框架入门教程

Playwright

www.einktodo.com 是我为 E-ink Todo List 设备开发的网站,为了减少在它上面的测试工作的时间,我使用了 Playwright 来进行 E2E 测试。

Playwright 是一个由微软开发的 E2E 测试框架,它可以模拟用户在浏览器中的操作,比如点击、输入、滚动等等。Playwright 支持多种浏览器,包括 Chrome、Firefox、Safari 等等,而且它还支持多种编程语言,比如 Javascript、Python、C# 等等。

在这篇文章中,我将向你展示如何使用 Playwright 来进行 E2E 测试。我们将会使用 Typescript 来编写测试代码。

安装 Playwright

在项目根目录下,运行以下命令来在项目中初始化 Playwright:

1
2
3
4
5
# npm
npm init playwright@latest

# yarn
yarn create playwright

初始化完成后,Playwright 会在项目中生成一个 playwright.config.ts 文件,和一个测试示例文件 example.spec.ts

Playwright 配置

生成的 playwright.config.ts 文件用 testDir 字段来指定测试文件的目录,projects 字段来指定义 Playwright 中的 Project 概念。

1
2
3
4
5
6
7
8
9
10
11
12
13
import { PlaywrightTestConfig } from "@playwright/test";

export default defineConfig({
// 测试文件目录
testDir: "tests",

// ...

// 项目配置
projects: [
// ...
],
});

第一个测试

初始化完成后,Playwright 会在测试文件目录中生成一个测试示例的测试文件 example.spec.ts,我们可以在这个文件中编写我们的第一个测试。

下面以 www.einktodo.com 的首页标题为例,来编写一个测试。

  1. @playwright/test中导入testexpect函数
  2. 使用test函数来定义一个测试
  3. 使用page.goto方法来打开网站
  4. 使用expecttoHaveTitle方法来判断页面的标题是否为E-ink Todo List
1
2
3
4
5
6
import { test, expect } from "@playwright/test";

test("E-ink Todo List 首页标题", async ({ page }) => {
await page.goto("https://www.einktodo.com");
await expect(page).toHaveTitle("E-ink Todo List");
});

运行测试

默认模式

运行所有的 Projects

1
2
3
4
5
# npm
npx playwright test

# yarn
yarn playwright test

运行一个 Project

1
2
3
4
5
# npm
npx playwright test --project=projectName

# yarn
yarn playwright test --project=projectName

UI 模式

1
2
3
4
5
# npm
npx playwright test --ui

# yarn
yarn playwright test --ui

Playwright 中的 Project

Playwright 中的 Project 概念用于组织多个可以并行运行的测试文件、Project 运行的依赖和运行结束的后置任务,以及 Project 的环境配置。

mindmap
  root((Project))

Projects 们的依赖关系

保存和使用登陆状态

参考

请我喝杯咖啡吧!

欢迎关注我的其它发布渠道