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:22【Front 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 :
- 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
Then enter from the command line
npx playwright install
Start installing browser binary dependenciesAfter 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
- 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.
- 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
- 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 https://playwright.dev/
await page.goto('https://playwright.dev/');
// 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
expect(name).toBe('Playwright');
});
Copy code
- 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 :
playwright.config.ts
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
playwright.config.ts
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 https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Share settings for all items below . See https://playwright.dev/docs/api/class-testoptions. */
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 https://playwright.dev/docs/trace-viewer 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 :
Fixture | Type | Description |
---|---|---|
page | Page | A separate page for this test run . |
context | BrowserContext | The isolation context for this test run .page This is also the case . Learn how to Configuration context . |
browser | Browser | Browsers are shared between tests to optimize resources . Learn how to Configure browser . |
browserName | string | 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.
expect(page.url()).toBe('https://my.start.url/');
});
});
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('https://playwright.dev/');
// 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 page.click('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
- Disable parallelization( Disable parallelism )
npx playwright test --workers=1
Copy code
- Choose a reporter
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
set PWDEBUG=1
npx playwright test
# Windows with PowerShell
$env:PWDEBUG=1
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 wikipedia.org
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 baidu.com
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 my.web.app
npx playwright codegen --load-storage=auth.json my.web.app
# 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.
playwright.$(selector)
Inquire about Playwright Selectors , Use practical Playwright Query engine , for example :
> playwright.$('.auth-form >> text=Log in');
<button>Log in</button>
Copy code
playwright.$$(selector)
And identical playwright.$
, But return all matching elements .
> playwright.$$('li >> text=John')
> [<li>, <li>, <li>, <li>]
Copy code
playwright.inspect(selector)
stay Elements Display elements in the panel ( If the corresponding browser DevTools Support it ).
> playwright.inspect('text=Log in')
Copy code
playwright.selector(element)
Generates a selector for a given element .
> playwright.selector($0)
"div[id="glow-ingress-block"] >> text=/.*Hello.*/"
Copy code
playwright.locator(selector)
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 Trace Viewer
- Run in headed mode( With GUI mode )
- Browser Developer Tools( Browser development tools )
- Run in Debug Mode( Run in debug mode )
- Selectors in Developer Tools Console( Selectors in the developer's workbench )
- Visual Studio Code debugger (Node.js)(Visual Studio Code debugger )
- Verbose API logs( The details of the API journal )
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 .
- Use
PWDEBUG=console
Parameter operation - Set breakpoint to pause execution
- Open the console panel in the browser developer tool
- Use
playwright
API
playwright.$(selector)
: Highlight the first occurrence of the selector content . This reflectspage.$
How to see the page .playwright.$$(selector)
: Highlight all selector contents that appear . This reflectspage.$$
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)
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 .
Python#
Support Playwright for Python.
Java#
Support Playwright for Java.
.NET#
Support Playwright for .NET.
copyright notice
author[Front end crocodile cub],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/135/202205111329375869.html
The sidebar is recommended
- babel7. 0 compatible with IE browser
- Nginx configuring reactrouter browserhistory browserrouter
- JS, react use html2canvas page screenshot and export
- Big data front-end visualization screen -- the road of front-end development
- [a quick introduction and comparison of multiple languages -- JavaScript, typescript, python, golang, trust, Java, ruby]
- Vue element admin login function, token filling, language conversion, routing setting
- Summation of corresponding position elements of multiple lists in Python
- Discussion on HTML page knowledge
- Using Ajax to realize non refresh paging
- HTTP format
guess what you like
Zhang San has a meal - did he eat the difference between get and post in HTTP?
The ultimate actual combat of the most complete tourism project based on spring boot + Vue front-end and back-end separation in history (with source code attached), none of them!!!
Vue basic grammar
LeetCode 217. There are duplicate elements
Pagoda does not configure the solution of SSL site accessing HTTPS and jumping to other websites
Vue3 isProxy
About the problem that the container will hang up after starting nginx in the docker container
Introduction to JavaScript
The core element of large-scale software design is to control complexity. What is the root cause?
What are the core elements of large-scale software design?
Random recommended
- C + + small job - create an array class arr to delete duplicate elements in the array
- Fancy front gradient
- Understanding of this in JavaScript
- Introduction to HTML + CSS Basics
- JavaScript makes a simple "aircraft war"
- Summary of Vue basics 14: what does vuex do?
- CSS introduction
- CSS introduction method
- CSS basic selector
- HTTPS pressure test you don't know
- Intersectionobserver and custom hooks
- Vue uses vis to implement topology map
- [Django CI system] if the front-end date is complete, it will be fully updated to the back-end; If the front-end date is incomplete, the date will not be updated to the back-end-20220510
- Is your endurance anxiety saved? 10 minute full electric vehicle technology is mature, netizen: it's useless to find a charging pile
- After reading 2000 applications for venture capital financing, I summed up the 20 elements that investors value most
- Diesel automobile double pickup truck leads the industry, and Jiangxi Isuzu no longer bows its head and acts recklessly
- Vue + elementui learning notes, use custom events to monitor the closing and opening events of the pop-up window of the introduced component
- Lazy loading usage based on element UI tree directory
- Vue encapsulates multiple request requests (solution for multiple domain names)
- Getting started with Vue
- Vuex getting started from 0 to 1
- Uniapp configuration element UI code block
- HTTP request method security: get, post, put, patch, delete, options, head, trace
- Axios source code analysis - Request interceptor
- Introduction to HTML tag list
- JavaScript output data
- JavaScript comments
- javascript Variables
- Introduction to JavaScript
- HTML and servlet cannot be connected together, and the set servlet cannot be implemented
- The back end returns HTML code. How can the front end preview
- About vue3 0 failed to load SVG through SVG sprite loader
- Antd Vue realizes login login page layout - with verification code verification function - Case
- Find a 5 respectively × 5 the sum of all rows, columns and elements on two diagonal lines of the matrix. (the input data is inconsistent with the output data)
- Raptor flowchart: random function generates a random array. The size of array elements is in the closed range of 100-999 and the length is 10. Find out the largest element and display its position
- How does PHP render some of the following JSON data into HTML
- The requested resource is not available when idea runs the HTML file
- JMeter generates HTML test report
- The spring of Huidong white potted pearl is a restless dream
- Vue3, complex watch implementation, solution For the second time