官方参考文档:Getting started - VS Code | Playwright
操作步骤:
创建用于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目录下新建测试文件
点击切换到Testing
有多个浏览器时,点击TEST EXPLORER后面的运行按钮下拉框,选择浏览器,点击这里的运行按钮,运行。
只有一个浏览器时,直接点击运行
(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 });
});
Vs code, typescript, xpath
对比Python+Selenium+Webdriver方案,
优点:(1)有官方IDE支持,使用较为简便,不需要使用Webdriver (2)支持的元素查找、定位方式更多 (3)加载时可以自动等待,操作事件的间隔时间可以统一配置
缺点:学习成本略高