playwright - "Playwright", end-to-end tests


outside_default.png

This article is based on playwright v1.34.3, node v18.16.0

NOTE: The playwright version is updated with node lts version updates, so make sure the node version matches the playwright version.

written in front

In the front-end development stage, testing is indispensable, which generally includes two types of testing: unit testing and end-to-end testing (e2e).

For components and functions, unit testing libraries such as jest, mocha, can easily do the job. But if it is a complex interaction scenario involving multiple modules on the page, e2e is essential. e2e can do:

  1. Simulate user actions in the browser

  2. Simulate the real browser operating environment

  3. Manipulate the runtime environment and obtain runtime data

  4. Take screenshots and compare the effects of each node

e2e, there are many tools available in the open source field, the famous one is google puppeteer. Of course, puppeteerit only provides chromethe ability to interact with the browser. To achieve e2e, you need to use such jesta test library.

Here I want to introduce another e2e testing tool, the protagonist of this article, which was born for e2e playwright("playwright").

what is playwright

「GitHub Copilot Answer」: "Playwright is a Node.js library for automating browser, single-page application, and cross-browser testing. It supports Chromium, Firefox, and WebKit, and can execute automated tests, crawlers in these browsers , performance testing and other tasks. Playwright also provides some convenient APIs, such as screenshots, recording videos, simulating user input, etc. At the same time, Playwright also supports multiple languages, such as JavaScript, TypeScript, Python, Java, and C#, etc.”

Why choose playwright

Compared with the "puppet master" ( puppeteer) ability to operate the browser, the playwright ( playwright) has the ability to support cross-operating systems , multiple browsers , and multiple development languages , which is obviously more powerful. (Domestic download and installation friendly!!)

First of all, playwrightfrom a famous family, it is a web automation testing framework developed by the Microsoft R&D team and released in early 2020. A strong open source community provides a stable guarantee playwrightfor the sustainable development of . Keep up with the browser version and release the adapted version in time.

Secondly, some of the core members come from puppeteerthe team and puppeteerare in the same line as the predecessors. So puppeteerthe projects can basically achieve seamless docking.

Finally, the most important ability is also prominently written in github's README.md, here is a brief overview:

  1. High stability, not easy to make mistakes, support "Auto-wait", "Web-first assertions", "Tracing";

  2. No trade-offs, no restrictions, "Multiple everything", "Trusted events", "Test frames, pierce Shadow DOM";

  3. Strong isolation, fast execution, "Browser contexts", "Log in once";

  4. Powerful tools, with "Codegen", "Playwright inspector", "Trace Viewer";

Install and use directly

As puppeteerwith , in addition to installation playwright, you also need to download the browser driver playwrightof , such as chromium, firefox, webkit.

Installation and initialization

Before installation, in order to speed up the download, you can set the download source .npmrcin PLAYWRIGHT_DOWNLOAD_HOST, such as:

PLAYWRIGHT_DOWNLOAD_HOST="https://cdn.npmmirror.com/binaries/playwright"

It is recommended npm init playwrightto playwright:

npm init playwright@latest

There will be a question and answer prompt, as follows:

Getting started with writing end-to-end tests with Playwright:
Initializing project in '.'
✔ Do you want to use TypeScript or JavaScript? · JavaScript
✔ Where to put your end-to-end tests? · tests
✔ Add a GitHub Actions workflow? (y/N) · false
✔ Install Playwright browsers (can be done manually via 'npx playwright install')? (Y/n) · false

in:

  1. You can choose the language type to initialize the project with, TypeScriptor JavaScript;

  2. You can choose the storage directory of the test file, the default is tests;

  3. You can choose whether to GitHub Actionsadd workflow for automated testing;

  4. You can choose whether to install the browser driver automatically, if you choose false, you need to install it manually.

Manually install the browser driver

npx playwright install

In addition, if you only want to download Chromium, you can use it --with-deps, such as:

npx playwright install --with-deps chromium

The download process is as follows:

Downloading Chromium 114.0.5735.35 (playwright build v1064) from https://cdn.npmmirror.com/binaries/playwright/builds/chromium/1064/chromium-mac-arm64.zip
122.8 Mb [====================] 100% 0.0s
Chromium 114.0.5735.35 (playwright build v1064) downloaded to /Users/liuyapeng/Library/Caches/ms-playwright/chromium-1064
Downloading FFMPEG playwright build v1009 from https://cdn.npmmirror.com/binaries/playwright/builds/ffmpeg/1009/ffmpeg-mac-arm64.zip
1 Mb [====================] 100% 0.0s
FFMPEG playwright build v1009 downloaded to /Users/liuyapeng/Library/Caches/ms-playwright/ffmpeg-1009

In order to avoid repeated downloads and facilitate browser management, playwrightthe browser will be downloaded to the default cache folder.

  • Windows: %USERPROFILE%\AppData\Local\ms-playwright

  • MacOS: ~/Library/Caches/ms-playwright

  • Linux: ~/.cache/ms-playwright

# 以macOS为例
ls ~/Library/Caches/ms-playwright
chromium-1064 ffmpeg-1009

run

In the process of initializing the project above, a test file has been generated with tests/example.spec.jsthe following content:

const { test, expect } = require('@playwright/test');

test('has title', async ({ page }) => {
  await page.goto('https://playwright.dev/');

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/Playwright/);
});
// ...

There is also a tests-examplesfolder with more test cases for reference.

At the same time, a playwright.config.jsconfiguration , the content is as follows:

const { defineConfig, devices } = require('@playwright/test');
module.exports = 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',
   projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
  ],
  // ...
});

Here you can configure the directory of the test file, the format of the test report, the browser for the test, etc.

Finally, run the tests:

npx playwright test

playwright testRead playwright.config.jsthe configuration, you can also add parameter settings after this command, such as specifying the browser to run --projectby , such as:

npx playwright test --project chromium

After the test is completed, you can view the test report, such as:

npx playwright show-report

a1e977ba78a433af4ce3a47c692ed043.png

Generate test code

For developers, writing test code is not difficult, the difficulty is that there is no time to write. For high-quality code, the number of test codes is often more than that of business codes. So, we need some tools to help us generate test code.

You can start a browser through the cli command, then manually operate, and finally generate the test code:

npx playwright codegen

0b6b791fb6bd37f616a237b8ddabb25e.gif

It is recommended to use vscodethe plugin to generate test code, which will be introduced later.

Via the vscode plugin

playwrightA vscodeplugin to easily generate test code, run tests, view test reports, etc.

install plugin

de5e3d65b23ba834fa039abb4b7b5346.png

use plugin

You can easily run the test by directly clicking "Test" in the main sidebar :

0abdf8701f361b7634ed6bcc1259f59b.png

playwrightClick "Record new use case" of the plug-in , and testsa new file will be automatically generated in , and the other processes are the same npx playwright codegen.

Use uivisual test cases

playwrightIt provides a very powerful function, that is, by using it to --uistart a page, you can easily run test cases, view test results, compare the test process frame by frame, etc. This is also very useful for design walkthroughs.

If you have used e2e tools cypress, the functions of the two are similar, but playwrightthe functions are more powerful.

npx playwright test --ui

53652a194427c530399a9d986996768d.gif

other uses

  • screenshot

Note: storybookWhen using the development component library, you can use playwrightthe official provided storywrightto automatically generate story screenshots, which is convenient for viewing the style of the component.

const { chromium } = require('playwright');
  (async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto('https://www.baidu.com');
    await page.screenshot({ path: `baidu.png` });
    await browser.close();
  })();
  • reptile

const { chromium } = require('playwright');
  (async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto('https://www.baidu.com');
    const title = await page.title();
    console.log(title);
    await browser.close();
  })();
  • Performance Testing

const { chromium } = require('playwright');
 (async () => {
   const browser = await chromium.launch();
   const page = await browser.newPage();
   await page.goto('https://www.baidu.com');
   const performanceTiming = JSON.parse(
     await page.evaluate(() => JSON.stringify(window.performance.timing))
   );
   console.log(performanceTiming);
   await browser.close();
 })();

Summarize

This article is a simple introduction playwrightto , mainly introducing its powerful end-to-end testing capabilities. For end-to-end testing, playwrightit provides a lot of convenience for us to write test cases, such as automatic waiting, automatic screenshots, automatic retry, automatic assertion, etc., including many visual tools, such as generating test code, generating test reports, generating Test recordings and more. It can be said that playwrightit can significantly improve our test development efficiency and allow us to focus more on writing test cases. It is a very recommended tool. Of course, playwrightthe capabilities are far more than that, and you need to go to the official website documents to explore by yourself.

reference link

  • https://playwright.dev/

  • https://jecyu.github.io/Fe-Auto-Testing/concepts/

- END -

About Qi Wu Troupe

Qi Wu Troupe is the largest front-end team of 360 Group, and participates in the work of W3C and ECMA members (TC39) on behalf of the group. Qi Wu Troupe attaches great importance to talent training, and has various development directions such as engineers, lecturers, translators, business interface people, and team leaders for employees to choose from, and provides corresponding technical, professional, general, and leadership training course. Qi Dance Troupe welcomes all kinds of outstanding talents to pay attention to and join Qi Dance Troupe with an open and talent-seeking attitude.

b8eab23426fc856003b997e84fcee0de.png

Guess you like

Origin blog.csdn.net/qiwoo_weekly/article/details/130959876