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:
Simulate user actions in the browser
Simulate the real browser operating environment
Manipulate the runtime environment and obtain runtime data
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, puppeteer
it only provides chrome
the ability to interact with the browser. To achieve e2e, you need to use such jest
a 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, playwright
from 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 playwright
for 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 puppeteer
the team and puppeteer
are in the same line as the predecessors. So puppeteer
the 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:
High stability, not easy to make mistakes, support "Auto-wait", "Web-first assertions", "Tracing";
No trade-offs, no restrictions, "Multiple everything", "Trusted events", "Test frames, pierce Shadow DOM";
Strong isolation, fast execution, "Browser contexts", "Log in once";
Powerful tools, with "Codegen", "Playwright inspector", "Trace Viewer";
Install and use directly
As puppeteer
with , in addition to installation playwright
, you also need to download the browser driver playwright
of , such as chromium
, firefox
, webkit
.
Installation and initialization
Before installation, in order to speed up the download, you can set the download source .npmrc
in PLAYWRIGHT_DOWNLOAD_HOST
, such as:
PLAYWRIGHT_DOWNLOAD_HOST="https://cdn.npmmirror.com/binaries/playwright"
It is recommended npm init playwright
to 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:
You can choose the language type to initialize the project with,
TypeScript
orJavaScript
;You can choose the storage directory of the test file, the default is
tests
;You can choose whether to
GitHub Actions
add workflow for automated testing;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, playwright
the 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.js
the 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-examples
folder with more test cases for reference.
At the same time, a playwright.config.js
configuration , 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 test
Read playwright.config.js
the configuration, you can also add parameter settings after this command, such as specifying the browser to run --project
by , such as:
npx playwright test --project chromium
After the test is completed, you can view the test report, such as:
npx playwright show-report
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
It is recommended to use vscode
the plugin to generate test code, which will be introduced later.
Via the vscode plugin
playwright
A vscode
plugin to easily generate test code, run tests, view test reports, etc.
install plugin
use plugin
You can easily run the test by directly clicking "Test" in the main sidebar :
playwright
Click "Record new use case" of the plug-in , and tests
a new file will be automatically generated in , and the other processes are the same npx playwright codegen
.
Use ui
visual test cases
playwright
It provides a very powerful function, that is, by using it to --ui
start 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 playwright
the functions are more powerful.
npx playwright test --ui
other uses
screenshot
Note:
storybook
When using the development component library, you can useplaywright
the official providedstorywright
to 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 playwright
to , mainly introducing its powerful end-to-end testing capabilities. For end-to-end testing, playwright
it 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 playwright
it 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, playwright
the 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.