如果您喜欢自动化和测试应用程序,那么您有个好消息。市场上有一种新工具可以吸引您的注意力并满足您对测试自动化的需求。
Playwright 是一个开源、强大且可靠的框架,用于对现代 Web 应用程序执行端到端自动化测试。它充满了诸如
从https://playwright.dev/了解更多信息
Playwright 安装、配置和创建我们的第一个测试非常容易上手。我们可以选择使用 Eclipse、WebStorm、IntelliJ、VSCode 或任何其他可选择语言(JavaScript、TypeScript、Java、Python 和 .Net)的 IDE。
我们将在这里看到如何将Playwright 与 TypeScript 和 VSCode 一起使用。
import { test, expect, Page } from '@playwright/test';
test.beforeEach(async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc');
});
test.describe('Add To Do Item', () => {
test('should allow me to add to do item', async ({ page }) => {
// Create a new to do item
await page.locator('.new-todo').fill("Do homework");
await page.locator('.new-todo').press('Enter');
// Make sure the list only has one to do item
await expect(page.locator('.view label')).toHaveText("Do homework");
})
});
技术01:
右键单击第 7 行或第 8 行的左侧开头
从可用选项中选择“运行测试”
测试执行将在左侧面板上发生和更新
技术02:
npx 编剧测试 my1stTest.spec.ts
2、测试执行,浏览器打开标准测试报告
按照 playwright.config.ts 文件中的默认配置,
我们可以根据需要更改配置。例如,使用无头:false
打开终端窗口并输入命令
npx Playwright codegen demo.playwright.dev/todomvc
这将在新的浏览器窗口中打开测试应用程序“ demo.playwright.dev/todomvc ”以及Playwright Inspector 窗口。
默认情况下,开始录制。一旦我们在应用程序中导航并执行用户交互,每一步都将记录在 Playwright Inspector 中。它具有开始/暂停/停止录制的选项以及生成代码的语言选择。
现在,将录制的脚本复制到一个新的测试文件“ myRecordedTest.spec.ts ”中。我们可以根据需要自定义测试并执行测试。
Playwright 能够为整个测试执行录制视频并将其保存在所需的位置。我们可以修改浏览器上下文并指定视频设置。在测试结束时关闭上下文也很重要。
下面是测试文件的代码:
import { chromium, test, expect } from '@playwright/test';let browser = null;let context = null;let page = null;test.describe('Add To Do Item', () => { test('Launch the browser', async() => { browser = await chromium.launch({ headless: false }) context = await browser.newContext({ recordVideo: { dir: './videos/', size: { width: 640, height: 480 }, } }); page = await context.newPage(); await page.goto('https://demo.playwright.dev/todomvc'); }) test('should allow me to add to do item', async () => { // Create a new to do item await page.locator('.new-todo').fill("Do homework"); await page.locator('.new-todo').press('Enter'); // Make sure the list only has one to do item await expect(page.locator('.view label')).toHaveText("Do homework"); await context.close(); await browser.close(); });});
在此代码中,我们在测试代码中指定了浏览器详细信息和上下文。我们希望这两个测试都按顺序进行。因此,更新 playwright.config.ts 中的fullyParallel : false属性
执行后,打开视频 文件夹,播放录制的视频。该视频将包含整个测试执行过程。
Playwright 能够截取元素或整个页面的屏幕截图并将它们保存在所需的位置。
下面是测试文件的代码:
await page.screenshot({ path: Date.now() + 'loginPageScreenshot.png', fullPage: true });await page.locator('.header').screenshot({ path: Date.now() + 'headerElementScreenshot.png' });
我们可以使用各种配置和选项自定义playwright.config.ts文件,例如测试目录、测试超时、断言超时、并行执行、测试失败时的重试次数、HTML 和 JSON 等报告类型、无头设置、自动截图、视频捕获和跟踪捕获失败。
这是 playwright.config.ts 文件的代码:
const config: PlaywrightTestConfig = { /* path of all the test files */ testDir: './tests', /* Maximum time one test can run for. */ timeout: 30 * 1000, expect: { /* Maximum time expect() should wait for the condition to be met. */ timeout: 5000 }, /* Run tests in files in parallel */ fullyParallel: false, /* Retry */ retries: 2, /* Reporter to use */ reporter: [["dot"],["json", { outputFile: "test-result.json"}],["html"]], use: { headless: false, screenshot: "only-on-failure", video: "retain-on-failure", /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */ actionTimeout: 0, /* Collect trace when retrying the failed test. */ trace: 'on-first-retry', },};
下面是测试文件的代码:
import { test, expect } from '@playwright/test';test.beforeEach(async ({ page }) => { await page.goto('https://demo.playwright.dev/todomvc');});test.describe('Add To Do Item', () => { test('should allow me to add to do item', async ({ page }) => { // Create a new to do item await page.locator('.new-todo').fill("Do homework"); await page.locator('.new-todo').press('Enter'); // Make sure the list only has one to do item await expect(page.locator('.view label')).toHaveText("Do homwork"); });});
观察index.html文件、test-result.json文件和test-results文件夹,其中包含2 次重试执行失败测试的屏幕截图 和视频 。
Playwright 有能力制作和直观地比较屏幕截图。在第一次执行中,它会生成参考屏幕截图,然后在后续执行中进行视觉比较。它使用带有各种选项的像素匹配 库。
await expect(page).toHaveScreenshot();
此命令将捕获页面截图,测试失败,并将截图保存在项目目录中作为参考。在随后的执行中,它将获取页面截图并与参考截图进行逐像素比较。
如果我们重命名参考截图,我们必须修改上面的命令。
await expect(page).toHaveScreenshot('newPage.png');
如果应用页面被修改,我们可以使用命令更新我们的参考截图
npx playwright test --update-snapshots
我们还可以指定最大允许的视觉差异。
await expect(page).toHaveScreenshot({ maxDiffPixels: 100 });
它允许我们根据页面布局定位元素。与 CSS 选择器结合使用时非常有用。
// Fill an input to the right of "Email".await page.locator('input:right-of(:text("Email"))').fill('data');// Click a button near the FAQs.await page.locator('button:near(.faqs)').click();// Click the button in the list closest to the "Subject".await page.locator('[type=radio]:left-of(:text("Subject"))').first().click();
除了相对定位器,它还为我们提供
从https://playwright.dev/docs/selectors了解更多信息
Playwright 拥有可以监控和修改网络流量的API 。它可以处理 HTTP 身份验证、HTTP 代理、处理、修改和中止请求、修改响应以及与 WebSocket 一起工作。
我们可以通过修改浏览器上下文在我们的测试应用程序中处理 HTTP 身份验证。
下面是测试文件的代码:
test('Launch the browser', async() => { browser = await chromium.launch({ headless: false }) const context = await browser.newContext({ httpCredentials: { username: 'myUserName', password: 'myPassword', }, }); page = await context.newPage(); await page.goto('https://demo.playwright.dev/todomvc'); })
在某些应用程序中,我们会遇到 text() 属性不起作用的文本元素。原因是这些元素不是文本元素,而是伪元素(多个元素的组合)。要从此类元素中获取文本,我们需要使用名为Tesseract JS的第三方库。这个库支持超过 100 种语言,可以在浏览器 或NodeJS 服务器中运行。
要安装 Tesseract JS,请运行命令
npm install tesseract.js
我们可以通过截屏将伪元素转换为图像。然后使用Tesseract 识别命令将图像转换为文本。
下面是测试文件的代码:
const Tesseract = require('tesseract.js');import { test } from '@playwright/test';test.describe('Convert Image to Text', () => { test('Test 01', async ({ page }) => { await page.goto('https://mySampleTestApplication'); const imageElement = await page.locator('.image'); const name = Date.now(); await imageElement.screenshot({ path: `${name}.png` }); await convertToText(`${name}.png`); });});async function convertToText(name: string) { let imgText = await Tesseract.recognize(`./${name}`);};
每个人都可以在 Playwright 中学习和探索很多东西。
让我们和Playwright一起玩吧。快乐学习!!
留言与评论(共有 0 条评论) “” |