使用playwright进行前端单元测试

596 阅读3分钟

创建playwright项目

  1. 先创建空项目文件夹
  2. 再在项目文件中,执行命令:pnpm create playwright

快速录制playwright脚本

npx playwright codegen: 此时会自动打开chrome浏览器,你输入待测试网址,即可开始测试,每次点击都会自动生成代码到另一个小窗,此时的脚本只是粗略脚本,还需要自行修正

通过ui界面执行playwright测试用例

npx playwright test --ui: 此时会打开chrome浏览器,你可以选择执行哪个用例

通过无头模式执行playwright测试用例

npx playwright test

生成测试报告

npx playwright show-report

检查筛选器

Command Line Interface | Playwright 中文文档 | Playwright 中文网 (bootcss.com)

通过调试模式执行测试用例

运行和调试测试 | Playwright 中文网 (nodejs.cn)

此模式下将打开浏览器窗口以及 Playwright 检查器。你可以使用检查器顶部的逐步按钮来逐步完成测试。或者,按播放按钮从头到尾运行测试。测试完成后,浏览器窗口将关闭。

测试用例执行异常时,录屏,并截图

playwright.config.ts

import { defineConfig, devices } from '@playwright/test'

export default defineConfig({
    use: {
        trace: 'on-first-retry',
        // 异常时录屏
        video: 'on-first-retry',
        // 异常时截屏
        screenshot: 'only-on-failure',
    },
})

自定义失败重试次数

默认:3次

重试 | Playwright 中文网 (nodejs.cn)

Playwright 测试结果分类

"passed" - 第一次运行时通过的测试; "flaky" - 第一次运行失败但重试时通过的测试; "failed" - 第一次运行失败且所有重试均失败的测试。

自动登录,并保持登录状态

验证 | Playwright 中文网 (nodejs.cn)

auth.setup.ts

import { test as setup } from '@playwright/test'

const authFile = 'playwright/.auth/user.json'

setup('authenticate', async ({ page }) => {
  await page.goto(
    'https://free_pan.gitee.io/archetype-backend-template/#/login'
  )
  await page.locator('[data-test="login-btn"]').click()
  await page.waitForURL(
    'https://free_pan.gitee.io/archetype-backend-template/#/demo/form/el-responsive-form'
  )
  await page.context().storageState({ path: authFile })
})

image.png

上面的方式需要通过编写代码,进行登录,但很多时候,登录还需填写验证码(可能是图片验证码,可能是手机验证码),一个普通的单元测试,没必要也没时间搞得像个爬虫程序一样去识别验证码。那么此时的正确做法是:

  1. 先通过npx playwright codegen --save-storage=auth.json, 会自动打开一个浏览器,然后在该浏览器中打开指定网页,执行登录,然后关闭浏览器,此时会将cookie信息和storage信息自动保存到auth.json文件中
  2. 再在单元测试代码中引入auth.json文件
import { test, expect } from "@playwright/test";

// 引入auth.json文件,当前文件的后续测试,都将在已登录的状态中进行
test.use({ storageState: "./auth.json" });

// 首层的单元测试都会基于autho.json的状态进行
test("test", async ({ page }) => {
  await page.goto(
    "https://free_pan.gitee.io/archetype-backend-template/#/demo/form/el-responsive-form"
  );
  await expect(page.getByLabel("Breadcrumb")).toContainText("el响应式表单");
});

test.describe(() => {  
    // 这个describe中的单元测试,都会基于user.json的状态运行
    test.use({ storageState: './user.json' });  

    test('user test', async ({ page }) => {  
        // page is authenticated as a user  
    });  
});

设置超时时间

超时 | Playwright 中文网 (nodejs.cn)

元素定位和过滤与事件触发和值填充

定位器 | Playwright 中文网 (nodejs.cn)

其他定位器 | Playwright 中文网 (nodejs.cn)

参数化测试

参数化测试 | Playwright 中文网 (nodejs.cn)

各种断言

断言 | Playwright 中文网 (nodejs.cn)

相关文章

使用 Playwright 搭建前端自动化测试工程 (上) - 知乎 (zhihu.com)

使用 Playwright 搭建前端自动化测试工程 (下) - 知乎 (zhihu.com)

playwright录制功能使用绕过登录操作 - peijiao - 博客园 (cnblogs.com)