Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Playwright Best Practices

Playwright Best Practices

This chapter summarizes the most important best practices in writing and maintaining Playwright tests, helping you write stable, maintainable tests.


Testing philosophy

Test user-visible behavior

Automated tests should verify what end users can see and interact with, rather than verifying code implementation details.

For example, tests should verify that the correct text is displayed on the page, buttons are clickable, and form submission redirects to the correct page - rather than verifying the return value of a JavaScript function or the internal structure of the DOM.

Example

// Not recommended: testing implementation details

expect

(

await page.

evaluate

(

(

)

=>

window.__store.

getState

(

)

.

user

.

name

)

)

  .

toBe

(

'runoob'

)

;

// Recommended: testing what users see

await expect

(

page.

getByText

(

'Welcome, runoob'

)

)

.

toBeVisible

(

)

;


Test isolation

Each test should be completely independent of other tests and not rely on the state of a previous test.

Playwright provides independent Contexts by default, but you should also ensure you do not rely on test execution order.

Example

// Not recommended: tests depending on each other

let createdId

;

test

(

'Create resource'

,

async

(

{

request

}

)

=>

{

 

const

resp

=

await request.

post

(

'/api/items'

)

;

  createdId

=

(

await resp.

json

(

)

)

.

id

;

 

// Shared state

}

)

;

test

(

'Use the created resource'

,

async

(

{

page

}

)

=>

{

  await page.

goto

(

`

/

items

/

$

{

createdId

}

`

)

;

 

// Depends on the result of the previous test

}

)

;

// Recommended: each test is self-contained

test

(

'Create and use resource'

,

async

(

{

request

,

page

}

)

=>

{

 

const

resp

=

await request.

post

(

'/api/items'

)

;

 

const

id

=

(

await resp.

json

(

)

)

.

id

;

  await page.

goto

(

`

/

items

/

$

{

id

}

`

)

;

  await expect

(

page.

getByText

(

'Resource details'

)

)

.

toBeVisible

(

)

;

}

)

;


Locator priority principle

Using Locators in the recommended order can improve test stability.

Precedence Method Applicable scenarios
1 getByRole() Element has a clear ARIA role
2 getByLabel() Form element has an associated label
3 getByPlaceholder() Input box has a placeholder
4 getByText() Element has clear text
5 getByAltText() Image has an alt attribute
6 getByTitle() Element has a title attribute
7 getByTestId() Fallback option
8 locator() CSS/XPath, choose last

Avoid using CSS class names as locators whenever possible.

Class names easily change due to style refactoring, causing widespread test failures.


Avoid unnecessary waits

Leverage Playwright's auto-waiting mechanism; avoid writing manual sleep or waitForTimeout。

Example

// Not recommended: hardcoded waits

await page.

waitForTimeout

(

3000

)

;

await page.

getByText

(

'Data loading complete'

)

.

click

(

)

;

// Recommended: rely on auto-waiting and assertions

await expect

(

page.

getByText

(

'Data loading...'

)

)

.

toBeHidden

(

{

timeout

:

10000

}

)

;

await page.

getByText

(

'Data loading complete'

)

.

click

(

)

;


Do not test third-party services

Only test what you can control; do not rely on the availability of third-party services.

Example

// Not recommended: relying on external CDNs or APIs

await page.

goto

(

'https://www.runoob.com/'

)

;

// The page may have loaded Google Analytics, external fonts, etc.

// Recommended: intercept third-party requests, mock external services

await page.

route

(

'**/analytics'

,

route

=>

route.

abort

(

)

)

;

await page.

route

(

'/external-api/'

,

route

=>

{

  route.

fulfill

(

{

json

:

{

status

:

'ok'

}

}

)

;

}

)

;


Use expect.soft() soft assertions

When checking multiple independent conditions, soft assertions can report all failures at once instead of stopping at the first failure.

Example

// Recommended: soft assertions check all fields at once

await expect.

soft

(

page.

getByLabel

(

'Username'

)

)

.

toBeVisible

(

)

;

await expect.

soft

(

page.

getByLabel

(

'Password'

)

)

.

toBeVisible

(

)

;

await expect.

soft

(

page.

getByLabel

(

'Email'

)

)

.

toBeVisible

(

)

;

await expect.

soft

(

page.

getByRole

(

'button'

,

{

name

:

'Register'

}

)

)

.

toBeEnabled

(

)

;

// If multiple fields are missing, report them all at once


Organize test files properly

Practice Description
Split files by functional module login.spec.ts、checkout.spec.ts etc.
Use describe for grouping Put related tests in test.describe() Medium
Make good use of beforeEach Extract repeated navigation and preparation steps into beforeEach
Descriptive test names A good name explains "what is done" and "what is expected"
Extract common code Extract helpers used by more than 3 files into a shared module
Do not over-DRY 2-3 lines of duplication are easier to maintain than over-abstraction

Troubleshooting common issues

Flaky tests

Causes and solutions of flaky tests:

Reason Solution
Hardcoded sleep is not long enough Use the auto-waiting mechanism instead of fixed waits
Relying on third-party services Use route() Mock external requests
Animations cause element positions to change In the configuration animations: 'disabled'
Data residue between tests Ensure each test creates and cleans up data independently
Time-related logic Use page.clock Freeze time

Locator cannot find an element

Diagnostic steps: