惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
GbyAI
GbyAI
爱范儿
爱范儿
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
Check Point Blog
M
MIT News - Artificial intelligence
量子位
宝玉的分享
宝玉的分享
MongoDB | Blog
MongoDB | Blog
V
Visual Studio Blog
罗磊的独立博客
F
Fortinet All Blogs
美团技术团队
博客园_首页
博客园 - 【当耐特】
L
LangChain Blog
月光博客
月光博客
腾讯CDC
The Cloudflare Blog
D
Docker
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

博客园 - coffee~

在微信端使用Openclaw的简单配置方法--WorkBuddy 使用Termux+Proot-distro+Ubuntu+zsh在手机端配置安装Openclaw,使用Skillhub安装skill, 接入企业微信 npm切换下载源为国内的镜像源 一加13刷氧系统--OxygenOS 15 for oneplus 13 Playwright使用Typescript实现在测试case文件中调用另一个文件中的方法 Cypress实现拖拽 git基本命令 Python获取星期几 cd命令切换目录简写 win10在任意位置安装Linux子系统WSL Ubuntu pixel刷机没有退出谷歌账号,无法跳过开机验证 Python在一个文件中引用另一个文件的所有变量 pycharm给代码批量添加tab/取消添加tab 用Pycharm把浏览器复制出来的headers/参数给字段和值分别加单引号 Python requests.get所有参数顺序、Python requests.post所有参数顺序 windows使用快捷按键进行截图、录屏 3个瓶盖可以兑换一瓶饮料,买了n瓶饮料,一共可以喝到多少瓶 Python由字符串生成字典 Python生成随机数 Python安装包国内镜像源 QQ飞车手游UI自动化测试尝试
使用Playwright进行Web页面UI自动化测试
coffee~ · 2024-06-28 · via 博客园 - coffee~

使用Playwright进行UI自动化测试实践尝试

官方参考文档:Getting started - VS Code | Playwright

操作步骤:

1.安装VS code

2.VS code安装Playwright Test for VSCode插件

3.添加测试文件夹和文件

创建用于UI自动化测试的文件夹,并在VS code中的file--open folder打开这个文件夹

vscode中间上方的搜索框点击选择Show and Run Commands

 

输入Install Playwright,选择Test:Install Playwright

浏览器选择Chromium和WebKit(Firefox根据需要选择),不勾选Use JavaScript,选中Add GitHub Actions workflow, 点击OK

这时,已经创建示例测试文件,切换到Explorer, 可以在tests目录下可以看到example.spec.ts文件,可以基于这个文件修改,也可以在tests目录下新建测试文件

 

4.运行

点击切换到Testing

 

有多个浏览器时,点击TEST EXPLORER后面的运行按钮下拉框,选择浏览器,点击这里的运行按钮,运行。

只有一个浏览器时,直接点击运行

5. 测试代码

(1)playwright.config.ts文件内容,  有中文注释的是新增或修改的内容

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

/**

 * Read environment variables from file.

 * https://github.com/motdotla/dotenv

 */

// require('dotenv').config();

/**

 * See https://playwright.dev/docs/test-configuration.

 */

export default defineConfig({

  testDir: './tests',

  /* Run tests in files in parallel */

  fullyParallel: true,

  /* Fail the build on CI if you accidentally left test.only in the source code. */

  forbidOnly: !!process.env.CI,

  /* Retry on CI only */

  retries: process.env.CI ? 2 : 0,

  /* Opt out of parallel tests on CI. */

  workers: process.env.CI ? 1 : undefined,

  /* Reporter to use. See https://playwright.dev/docs/test-reporters */

  reporter: 'html',

  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */

  use: {

    /* Base URL to use in actions like `await page.goto('/')`. */

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */

    trace: 'on-first-retry',

    launchOptions: {

      //设置chronium全屏,窗口最大化

      args: ['--start-maximized'],

      //设置操作步骤等待时间为5秒

      slowMo: 5000,

    },

    //失败时截图

    screenshot: 'only-on-failure',

    //开启录屏,失败时录屏 选项是 'retain-on-failure'

    video: {

      mode: 'on',

      size: { width: 1920, height: 1080 }

      },

    contextOptions: { recordVideo: { dir: 'test-results/videos/' } }

  },

  /* Configure projects for major browsers */

  projects: [

    //添加setup 

    // Setup project

    { name: 'setup', testMatch: /.*\.setup\.ts/,

      use: { 

      //分辨率使用全屏设置,注释下面的devices语句

      //...devices['Desktop Chrome'], 

        viewport: null,

      },

    },

    {

      name: 'chromium',

      use: { 

        //分辨率使用全屏设置,注释下面的devices语句

        //...devices['Desktop Chrome'], 

        storageState: 'playwright/.auth/user.json',

        viewport: null,

      },

      dependencies: ['setup'],

    },

    {

      name: 'firefox',

      use: { ...devices['Desktop Firefox'] },

    },

    {

      name: 'webkit',

      use: { ...devices['Desktop Safari'] },

    },

    /* Test against mobile viewports. */

    // {

    //   name: 'Mobile Chrome',

    //   use: { ...devices['Pixel 5'] },

    // },

    // {

    //   name: 'Mobile Safari',

    //   use: { ...devices['iPhone 12'] },

    // },

    /* Test against branded browsers. */

    // {

    //   name: 'Microsoft Edge',

    //   use: { ...devices['Desktop Edge'], channel: 'msedge' },

    // },

    // {

    //   name: 'Google Chrome',

    //   use: { ...devices['Desktop Chrome'], channel: 'chrome' },

    // },

  ],

  /* Run your local dev server before starting the tests */

  // webServer: {

  //   command: 'npm run start',

  //   url: 'http://127.0.0.1:3000',

  //   reuseExistingServer: !process.env.CI,

  // },

  //设置事件超时时间

  timeout: 120000,

  globalTimeout: 600000,

});

(2)test目录下的.spec.ts文件,  内容:

import { test, expect } from '@playwright/test';

test('visit aix', async ({ page }) => {

  await page.goto('页面链接1');

  await expect(page).toHaveTitle(/title/);

});

(3)登录,保存登录信息

在项目文件夹根目录下创建文件夹  playwright/.auth,把playwright/.auth添加到.gitignore文件

在tests目录下创建auth.setup.ts文件

auth.setup.ts文件内容:

import { test as setup, expect, chromium } from '@playwright/test';

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

       setup('authenticate', async ({ page }) => {

         // Perform authentication steps. Replace these actions with your own.

         await page.goto('页面地址0');

         await page.click("xpath1");

         await page.fill("#username", "xxxxxx");

         await page.fill("#password", "xxxxxx");

         await page.click("//button[@type='submit']");

         // Wait until the page receives the cookies.

         // Sometimes login flow sets cookies in the process of several redirects.

         // Wait for the final URL to ensure that the cookies are actually set.

         await page.waitForURL('页面地址1');

         await expect(page.locator("//div[contains(@class, 'username')]/span")).toHaveText('xxx');

         // End of authentication steps.

         await page.context().storageState({ path: authFile });

       });

2.     学习成本

Vs code, typescript, xpath

3.     优点与缺点

对比Python+Selenium+Webdriver方案,

优点:(1)有官方IDE支持,使用较为简便,不需要使用Webdriver  (2)支持的元素查找、定位方式更多 (3)加载时可以自动等待,操作事件的间隔时间可以统一配置

缺点:学习成本略高

我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=2c71a7ei6scgk