current position:Home>"Automated testing" a new generation of Web front-end automated testing framework - playwright, get started quickly!

"Automated testing" a new generation of Web front-end automated testing framework - playwright, get started quickly!

2022-05-15 05:01:22Front end crocodile cub

This article has participated in 「 New people's creation ceremony 」 Activities , Start the road of nuggets creation together .

playwright Get started

How to install projects in Intranet depends on

Be careful : Want to run playwright You need to download the binary file of the relevant browser

Because by default ,Playwright From Microsoft CDN Download browser binaries .

The intranet will block direct access to public resources , So you can't download directly through the intranet .

terms of settlement

  1. On the Internet , Create a folder, then call out the command line in this directory and enter npm i -D @playwright/test

Page directory changes , And the command line appears added 193 packages in 15s Represents that the download is complete

  1. Then enter from the command line npx playwright install Start installing browser binary dependencies

  2. After downloading, enter the corresponding directory , An example is :C:\Users\winches\AppData\Local\ms-playwright

It will be as shown in the figure 4 Select a file to copy


  1. Will be selected 4 Paste a file into the intranet ms-playwright Under the document


playwright Quick start

Playwright Introduce

Playwright It's a Testing and automation framework , It can realize the automatic interaction of web browser . In short , You can write code to open the browser , Use code to realize the function of using all web browsers . Automated scripts can achieve Navigate to URL、 Input text 、 Click the button and extract the text And so on .Playwright The most surprising feature is that it can Process multiple pages at the same time without waiting , Will not be blocked .

Playwright Support for most browsers , for example Google Chrome、Firefox、 Use Chromium Kernel Microsoft Edge And use WebKit Kernel Safari. Cross browser network automation yes Playwright The strengths of , You can effectively execute the same code for all browsers . Besides ,Playwright Support for various programming languages , for example Node.js、Python、Java and .NET. You can write code to open a web site and interact with it in any of these languages .

Use Node.js establish playwright project

Playwright Have their own test runner For end-to-end testing , We call it Playwright Test.

  1. Initialize the project and install playwright/test library , It only takes two simple commands to complete
npm init -y
npm i -D @playwright/test
 Copy code 
  1. Create a simple script test-1.spec.ts
const { test, expect } = require('@playwright/test');

//  The test case 
test('basic test', async ({ page }) => {
  //  Open a page and jump to
  await page.goto('');
  //  Through the class selector , The selected category is navbar__title The elements of the innerText
  const name = await page.innerText('.navbar__title');
  //  Whether the assertion check matches 
 Copy code 
  1. Now run your test script
npm playwright test
 Copy code 

Playwright Test Just used Chromium Browser with no GUI(headless) Run a test in the same way (Playwright Test). Let's tell it to use GUI(headed) Run the browser in mode :

npx playwright test --headed
 Copy code 

What about other browsers ? Let's use Firefox Run the same test (Playwright Test):

npx playwright test --browser=firefox
 Copy code 

Last , On all three browsers :

npx playwright test --browser=all
 Copy code 

The configuration document

Enjoy Playwright Test All functions provided , You also need to create a configuration file playwright.config.ts( or playwright.config.js).

Here are some sample configurations :


import { PlaywrightTestConfig } from "@playwright/test"; 
let config: PlaywrightTestConfig = { 	
     timeout: 6 * 60 * 1000,  //  Each test case timed out  
     globalTimeout: 60 * 1000, //  Total timeout  
     testDir: "./demo",// Test directory  
     reporter: [["html", { outputFolder: "./", open: "always" }]],// Test report  
     use: { 		
        launchOptions: { 			
        headless: false, // Not headless 
    contextOptions: { 			
    viewport: {   // Window view size  
        width: 1400,   				
        height: 900, 			
    //baseURL: process.env.TENANT_URL, //  Basics URL 
    screenshot: "only-on-failure", //  Screenshot on failure  
    trace: "retain-on-failure",//  Tracking records on failure  
    browserName: "webkit", //  Test browser  
export default config;

 Copy code 

It can also be done through npm init [email protected] Project name One click project generation and configuration

There are out of the box configurations


import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';
const config: PlaywrightTestConfig = {
  /*  The directory included in the test  */
  testDir: './tests',
  /*  A test can run expect() The maximum time to wait for the condition to be met  */
  timeout: 30 * 1000,
  expect: {
    /** * expect() The maximum time to wait for the conditions to be met  *  for example , stay 'await expect(locator).toHaveText()' */
    timeout: 5000
  /*  If you accidentally exit the test , Can't be in CI Build on . Only in the source code  */
  forbidOnly: !!process.env.CI,
  /*  Only in CI Try again on  */
  retries: process.env.CI ? 2 : 0,
  /*  Choose to exit CI Parallel testing of  */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See */
  reporter: 'html',
  /*  Share settings for all items below . See */
  use: {
    /*  Each operation ( Such as “click()”) The longest time it can take . The default value is 0( unlimited ) */
    actionTimeout: 0,
    /*  stay “ Waiting for page ” And so on URL. go to (“/”) */
    // baseURL: 'http://localhost:3000',

    /*  Collect trace when retrying failed tests . See  Copy code 

More configuration information can be viewed : Configuration information

Test fixtures

Test fixtures Jump to the official website

You notice the above The test script Accessible parameters {page}

test('basic test', async ({ page }) => {
 Copy code 

We call these parameters fixtures..Fixtures Is the object created for each test run .Playwright Test Loaded these fixtures, You can also add your own fixtures. When running tests ,Playwright Test Will view each test statement , Analysis and testing required fixtures And prepare these for the test fixtures .

Here are the predefined..., which you may often use fixtures A list of :

pagePage A separate page for this test run .
contextBrowserContext The isolation context for this test run .page This is also the case . Learn how to Configuration context .
browserBrowser Browsers are shared between tests to optimize resources . Learn how to Configure browser .
browserNamestring The name of the browser currently running the test . or chromium,firefox or webkit.

Test and assert features

If you are familiar with Jest、Mocha and Ava Wait for the test run program , You will find Playwright Test Grammar is very familiar with .

Playwright Test Use expect Library to test assertions . It uses methods specific to Playwright It is extended by the matcher of , To achieve greater test engineering .

These are what you can Basic operations performed by testing

Focus test

You can focus on some tests . When there are key tests , Only they run .

test.only('focus this test', async ({ page }) => {
  //  Run only key tests throughout the project .
 Copy code 

Skip the test

You can skip the test by setting some conditions :

test('skip this test', async ({ page, browserName }) => {
  test.skip(browserName === 'firefox', 'Still working on it');
 Copy code 

Group test

You can group tests to give them a logical name or precede the scope / Then associate to group .

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

test.describe('two tests', () => {
  test('one', async ({ page }) => {
    // ...

  test('two', async ({ page }) => {
    // ...
 Copy code 

Test the hook (test hooks)

You can use test.beforeAll and test.afterAll Hook to set and remove resources shared between tests . You can use test.beforeEach and test.afterEach Hooks set and remove resources for each test separately .

// example.spec.js
const { test, expect } = require('@playwright/test');

test.describe('feature foo', () => {
  test.beforeEach(async ({ page }) => {
    //  Go to start... Before each test  url.
    await page.goto('https://my.start.url/');

  test('my test', async ({ page }) => {
    //  Assert the use of  expect API.
 Copy code 

Write assertion (expect)

Playwright Test Use expect Library to test assertions . It provides many matchers , toEqual, toContain, toMatch, toMatchSnapshot wait .

take expect With all kinds of Playwright Combination of methods , To achieve the test goal :

  • page.isVisible(selector[, options])#
  • page.waitForSelector(selector[, options])#
  • page.textContent(selector[, options])#
  • page.getAttribute(selector, name[, options])#
  • page.screenshot([options])#
  • stay Assertion Learn more in the guide
// example.spec.ts
import { test, expect } from '@playwright/test';

test('my test', async ({ page }) => {
  await page.goto('');

  //  Expected title “ contain ” Substring .
  await expect(page).toHaveTitle(/Playwright/);

  //  Expectation attribute “ Strictly equal to the ” This value .
  await expect(page.locator('text=Get Started').first()).toHaveAttribute('href', '/docs/intro');

  await'text=Get Started');
  //  Expect some text to be visible on the page .
  await expect(page.locator('text=Introduction').first()).toBeVisible();
 Copy code 

Notice how running this test outputs :


Learn the command line

There are common Command line Parameters .

  • Run tests in headed browsers( With browser UI mode )
npx playwright test --headed
 Copy code 
  • Run tests in a particular browser( Run in the specified browser )
npx playwright test --browser=webkit
 Copy code 
  • Run tests in all browsers( Run tests on all browsers )
npx playwright test --browser=all
 Copy code 
  • Run a single test file( Single test file )
npx playwright test tests/todo-page.spec.ts
 Copy code 
  • Run a set of test files( Multiple test files )
npx playwright test tests/todo-page/ tests/landing-page/
 Copy code 
  • Run a test with specific title( Run the test with a specific title )
npx playwright test -g "add a todo item"
 Copy code 
  • Run tests in parallel - that's the default( Parallel test - Default )
npx playwright test
 Copy code 
npx playwright test --workers=1
 Copy code 
npx playwright test --reporter=html
 Copy code 
  • Ask for help ( Ask for help )
npx playwright test --help
 Copy code 

Run in debug mode (GUI Tools )

Playwright Inspector It's a GUI Tools , Can help create and debug Playwright Script .

# Linux/macOS
PWDEBUG=1 npx playwright test
 # Windows with cmd.exe
npx playwright test
 # Windows with PowerShell
npx playwright test
 Copy code 

Generate test code automatically

Use Playwright No need to write a line of code , We just need to manually operate the browser , It will record our actions , And then automatically generate code scripts .

Here's the recording command codegen, Just one line .

npx playwright codegen
 Copy code 

perform codegen And run the browser . Playwright Inspector User interactions will be recorded and generated JavaScript Code codegen Will try to generate a text-based elastic selector .

( Shown here )Playwright Inspector


codegen You can use --help see , If it is simple to use, it is to add url link , If you have other needs, you can add options.

options meaning :

  • -o: Save the recorded script to a file
  • --target: Specify the language in which the script is generated , The default is Playwright Test
  • -b: Specify browser driver

such as , I want to be in Search for , use chromium drive , Save results as test1.spec.ts Of ts file .

npx playwright codegen -b chromium -o ./test2.spec.ts --target=javascript
 Copy code 


After the command line input, the browser will be opened automatically , Then you can see that every move on the browser is automatically translated into code , As shown below .

adopt vscode Playwright Test for VScode Plug in generation code

Record new tests by performing test actions in the browser .


Keep verified status

perform codegen And designate --save-storage Parameter to save cookies and localStorage. This is useful for recording the authentication step separately and reusing it later .

npx playwright codegen --save-storage=auth.json
# Perform authentication and exit.
# auth.json will contain the storage state.
 Copy code 

Use --load-storage Parameter to load the previous storage . In this way , be-all cookies and localStorage Will be restored , Make most of web The application enters the authentication state .

npx playwright open --load-storage=auth.json
npx playwright codegen --load-storage=auth.json
# Perform actions in authenticated state.
 Copy code 

With custom settings Codegen

If you want to use in some non-standard settings codegen ( for example , Use browserContext.route(url, handler)), You can call page.pause() , It will open a separate window with code generation controls .

const { chromium } = require('playwright');

(async () => {
  // Make sure to run headed.
  const browser = await chromium.launch({ headless: false });

  // Setup context however you like.
  const context = await browser.newContext({ /* pass any options */ });
  await context.route('**/*', route => route.continue());

  // Pause the page, and start recording manually.
  const page = await context.newPage();
  await page.pause();
 Copy code 

Check the selector (selectors)

stay open or codegen period , You can browse in any browser developer tools The following... Are used in the console API.



Inquire about Playwright Selectors , Use practical Playwright Query engine , for example :

> playwright.$('.auth-form >> text=Log in');

<button>Log in</button>
 Copy code 


And identical playwright.$, But return all matching elements .

> playwright.$$('li >> text=John')

> [<li>, <li>, <li>, <li>]
 Copy code 


stay Elements Display elements in the panel ( If the corresponding browser DevTools Support it ).

> playwright.inspect('text=Log in')
 Copy code 


Generates a selector for a given element .

> playwright.selector($0)

"div[id="glow-ingress-block"] >> text=/.*Hello.*/"
 Copy code 


Use practical Playwright Query engine queries Playwright Elements , for example :

> playwright.locator('.auth-form', { hasText: 'Log in' });

> Locator ()
>   - element: button
>   - elements: [button]
 Copy code 

Debugging tools (Debugging)

Playwright Scripts are used with existing debugging tools , for example Node.js Debugger and browser development tools . Playwright It also introduces new debugging functions for browser automation .

Playwright Inspector

Playwright Inspector It's a GUI Tools , Can help create and debug Playwright Script . This is our default recommended script troubleshooting tool .


Playwright Trace Viewer

Playwright Trace Viewer It's a GUI Tools , It can help to troubleshoot the test run in the way of post analysis .


Browser development tools (Browser Developer Tools)

You can go to Chromium、Firefox and WebKit Using browser development tools , At the same time GUI(Headed) mode Playwright Script . Developer tools help :

  • Check DOM Tree and Find element selector
  • During execution ** Check the console log (** Or learn how to adopt API Read log
  • Check Internet activities And other developer tool functions


Use page.pause() The way is to pause Playwright A simple way to execute a script and check a page in a developer tool . It will also open Playwright Inspector To help debug .

about Chromium: You can also open developer tools through the launch option .

await chromium.launch({ devtools: true });
 Copy code 

Be careful about WebKit: Start during execution WebKit Inspector Will stop Playwright Script continues

Selector in developer tools console (Selectors in Developer Tools Console)

Selector in developer tools console

Use... In debug mode PWDEBUG=console Runtime , It can be used in the developer tool console playwright object .

  1. Use PWDEBUG=console Parameter operation
  2. Set breakpoint to pause execution
  3. Open the console panel in the browser developer tool
  4. Use playwright API
    • playwright.$(selector): Highlight the first occurrence of the selector content . This reflects page.$ How to see the page .
    • playwright.$$(selector): Highlight all selector contents that appear . This reflects page.$$ How to see the page .
    • playwright.inspect(selector): Check “ Elements ” Selector in panel .
    • playwright.clear(): Clear existing highlights .
    • playwright.selector(element): Generate a selector pointing to the element .


Visual Studio Code debugger (Node.js)

Visual Studio Code debugger

VS Code The debugger can be used to pause and resume through breakpoints Playwright Script execution . The debugger can be configured in two ways .

Supported languages

Playwright API Support for multiple languages

JavaScript and TypeScript#

Support Playwright for Node.js .


Support Playwright for Python.


Support Playwright for Java.


Support Playwright for .NET.

copyright notice
author[Front end crocodile cub],Please bring the original link to reprint, thank you.

Random recommended