一款强大的端到端测试工具Playwright介绍

2023-01-30 09:45:24
目录
Playwright跨浏览器支持多编程语言保存登录信息执行环境的隔离测试框架

Playwright

Playwright>

作为一款端到端的测试工具,在过去短短的两年时间里,Playwright 已经赢得了越来越多开发人员的青睐。Best of JS 网站对比了各个测试框架 2021 年在 GitHub 新增的 star 数量,Playwright 位于榜首位置,其受欢迎的程度可见一斑。本文将对 Playwright 的特点做一些的介绍。

跨浏览器

Playwright>

支持多编程语言

Playwright>

const { chromium, firefox, webkit } = require('playwright');
(async () => {
  const browser = await chromium.launch();  // Or 'firefox' or 'webkit'.
  const page = await browser.newPage();
  await page.goto('http://example.com');
  // other actions...
  await browser.close();
})();

保存登录信息

在测试中,经常会有页面登陆的场景,在单元测试中为了提高效率避免多次登陆,Playwright>

执行环境的隔离

Playwright>

const { chromium } = require('playwright');
// Create a Chromium browser instance
const browser = await chromium.launch();
// Create two isolated browser contexts
const userContext = await browser.newContext();
const adminContext = await browser.newContext();
// Create pages and interact with contexts independently

选择器

Playwright 支持多种元素定位方式,比如 CSS 选择器、XPath 选择器等,而且使用起来比较友好。

// Clicks a <button> that has either a "Log in" or "Sign in" text.
await page.locator('button:has-text("Log in"), button:has-text("Sign in")').click();

自动等待

Playwright 在与元素交互操作(如点击操作)之前,会进行一系列可操作性检查,以确保这些行动按预期运行。它会自动等待所有相关检查通过,然后才执行相关的操作。这样可以避免元素因为没有渲染,而导致交互操作的失败。在其他的一些测试框架中,需要开发人员自己手动设置等待时间,而且手动设置的时间往往也是不精确的。

测试框架

Playwright>

import { test, expect } from '@playwright/test';
test('basic test', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  const title = page.locator('.navbar__inner .navbar__title');
  await expect(title).toHaveText('Playwright');
});

本文只对 Playwright 做了一些简单的介绍,并未深入的展开,从当前的使用的趋势和热度来看,还是有必要对它进行一定的了解和关注,更多关于端到端测试工具Playwright的资料请关注易采站长站其它相关文章!