docs: align Node.js code snippets with ESLint (#23916)

This commit is contained in:
Max Schmitt 2023-06-27 11:53:53 +02:00 committed by GitHub
parent 71650f9bd1
commit 9980f054bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
59 changed files with 400 additions and 368 deletions

View File

@ -147,7 +147,7 @@ const USER = 'github-username';
'Authorization': `token ${process.env.API_TOKEN}`,
}
});
})()
})();
```
## Sending API requests from UI tests
@ -180,7 +180,7 @@ test.beforeAll(async ({ playwright }) => {
'Authorization': `token ${process.env.API_TOKEN}`,
},
});
})
});
test.afterAll(async ({ }) => {
// Dispose all responses.
@ -227,7 +227,7 @@ test.beforeAll(async ({ playwright }) => {
'Authorization': `token ${process.env.API_TOKEN}`,
},
});
})
});
test.afterAll(async ({ }) => {
// Dispose all responses.
@ -289,7 +289,7 @@ automatically update browser cookies if [APIResponse] has `Set-Cookie` header:
```js
test('context request will share cookie storage with its browser context', async ({ page, context }) => {
await context.route('https://www.github.com/', async (route) => {
await context.route('https://www.github.com/', async route => {
// Send an API request that shares cookie storage with the browser context.
const response = await context.request.fetch(route.request());
const responseHeaders = response.headers();
@ -318,7 +318,7 @@ create a new instance of [APIRequestContext] which will have its own isolated co
test('global context request has isolated cookie storage', async ({ page, context, browser, playwright }) => {
// Create a new instance of APIRequestContext with isolated cookie storage.
const request = await playwright.request.newContext();
await context.route('https://www.github.com/', async (route) => {
await context.route('https://www.github.com/', async route => {
const response = await request.fetch(route.request());
const responseHeaders = response.headers();

View File

@ -7,7 +7,7 @@ context.
```js
// Listen for all console logs
page.on('console', msg => console.log(msg.text()))
page.on('console', msg => console.log(msg.text()));
// Listen for all console events and handle errors
page.on('console', msg => {
@ -23,8 +23,8 @@ await page.evaluate(() => {
const msg = await msgPromise;
// Deconstruct console log arguments
await msg.args()[0].jsonValue() // hello
await msg.args()[1].jsonValue() // 42
await msg.args()[0].jsonValue(); // hello
await msg.args()[1].jsonValue(); // 42
```
```java

View File

@ -25,10 +25,9 @@ const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
function dumpFrameTree(frame, indent) {
console.log(indent + frame.url());
for (const child of frame.childFrames()) {
for (const child of frame.childFrames())
dumpFrameTree(child, indent + ' ');
}
}
})();
```
@ -733,8 +732,8 @@ If the function, passed to the [`method: Frame.evaluateHandle`], returns a [Prom
**Usage**
```js
// Handle for the window object
const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
aWindowHandle; // Handle for the window object.
```
```java
@ -2137,7 +2136,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
for (let currentURL of ['https://google.com', 'https://bbc.com']) {
for (const currentURL of ['https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
const element = await page.mainFrame().waitForSelector('img');
console.log('Loaded image: ' + await element.getAttribute('src'));

View File

@ -1750,8 +1750,8 @@ For example, given the following element:
```
```js
const locator = page.locator("id=favorite-colors");
await locator.selectOption(["R", "G"]);
const locator = page.locator('id=favorite-colors');
await locator.selectOption(['R', 'G']);
await expect(locator).toHaveValues([/R/, /G/]);
```

View File

@ -14,7 +14,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
log: (name, severity, message, args) => console.log(`${name} ${message}`)
}
});
...
// ...
})();
```

View File

@ -338,7 +338,7 @@ Emitted when a file chooser is supposed to appear, such as after clicking the `
respond to it via setting the input files using [`method: FileChooser.setFiles`] that can be uploaded after that.
```js
page.on('filechooser', async (fileChooser) => {
page.on('filechooser', async fileChooser => {
await fileChooser.setFiles('/tmp/myfile.pdf');
});
```
@ -1508,7 +1508,7 @@ Console.WriteLine(await page.EvaluateAsync<int>("1 + 2")); // prints "3"
```js
const bodyHandle = await page.evaluate('document.body');
const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
const html = await page.evaluate<string, HTMLElement>(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
await bodyHandle.dispose();
```
@ -1562,8 +1562,8 @@ promise to resolve and return its value.
**Usage**
```js
// Handle for the window object.
const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window));
aWindowHandle; // Handle for the window object.
```
```java
@ -4698,7 +4698,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
for (let currentURL of ['https://google.com', 'https://bbc.com']) {
for (const currentURL of ['https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
const element = await page.waitForSelector('img');
console.log('Loaded image: ' + await element.getAttribute('src'));

View File

@ -11,7 +11,7 @@ import { test, expect } from '@playwright/test';
test('status becomes submitted', async ({ page }) => {
// ...
await page.locator('#submit-button').click()
await page.locator('#submit-button').click();
await expect(page.locator('.status')).toHaveText('Submitted');
});
```

View File

@ -12,12 +12,12 @@ const playwright = require('playwright');
const context = await browser.newContext();
const page = await context.newPage();
try {
await page.locator("text=Foo").click({
await page.locator('text=Foo').click({
timeout: 100,
})
});
} catch (error) {
if (error instanceof playwright.errors.TimeoutError)
console.log("Timeout!")
console.log('Timeout!');
}
await browser.close();
})();

View File

@ -1302,9 +1302,13 @@ By default, the `data-testid` attribute is used as a test id. Use [`method: Sele
```js
// Set custom test id attribute from @playwright/test config:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
testIdAttribute: 'data-pw'
}
},
});
```
## template-locator-get-by-text
@ -1327,19 +1331,19 @@ You can locate by text substring, exact string, or a regular expression:
```js
// Matches <span>
page.getByText('world')
page.getByText('world');
// Matches first <div>
page.getByText('Hello world')
page.getByText('Hello world');
// Matches second <div>
page.getByText('Hello', { exact: true })
page.getByText('Hello', { exact: true });
// Matches both <div>s
page.getByText(/Hello/)
page.getByText(/Hello/);
// Matches second <div>
page.getByText(/^hello$/i)
page.getByText(/^hello$/i);
```
```python async
@ -1503,8 +1507,8 @@ You can fill the input after locating it by the placeholder text:
```js
await page
.getByPlaceholder("name@example.com")
.fill("playwright@microsoft.com");
.getByPlaceholder('name@example.com')
.fill('playwright@microsoft.com');
```
```java

View File

@ -497,7 +497,7 @@ You can introduce fixtures that will provide a page authenticated as each role.
Below is an example that [creates fixtures](./test-fixtures.md#creating-a-fixture) for two [Page Object Models](./pom.md) - admin POM and user POM. It assumes `adminStorageState.json` and `userStorageState.json` files were created in the global setup.
```js title="playwright/fixtures.ts"
import { test as base, Page, Locator } from '@playwright/test';
import { test as base, type Page, type Locator } from '@playwright/test';
// Page Object Model for the "admin" page.
// Here you can add locators and helper methods specific to the admin page.
@ -579,10 +579,9 @@ fs.writeFileSync('playwright/.auth/session.json', JSON.stringify(sessionStorage)
const sessionStorage = JSON.parse(fs.readFileSync('playwright/.auth/session.json', 'utf-8'));
await context.addInitScript(storage => {
if (window.location.hostname === 'example.com') {
for (const [key, value] of Object.entries(storage)) {
for (const [key, value] of Object.entries(storage))
window.sessionStorage.setItem(key, value);
}
}
}, sessionStorage);
```

View File

@ -65,7 +65,8 @@ If working with a database then make sure you control the data. Test against a s
In order to write end to end tests we need to first find elements on the webpage. We can do this by using Playwright's built in [locators](./locators.md). Locators come with auto waiting and retry-ability. Auto waiting means that Playwright performs a range of actionability checks on the elements, such as ensuring the element is visible and enabled before it performs the click. To make tests resilient, we recommend prioritizing user-facing attributes and explicit contracts.
```js
👍 page.getByRole('button', { name: 'submit' })
// 👍
page.getByRole('button', { name: 'submit' });
```
#### Use chaining and filtering
@ -92,13 +93,15 @@ Your DOM can easily change so having your tests depend on your DOM structure can
```js
👎 page.locator('button.buttonIcon.episode-actions-later')
// 👎
page.locator('button.buttonIcon.episode-actions-later');
```
Use locators that are resilient to changes in the DOM.
```js
👍 page.getByRole('button', { name: 'submit' })
// 👍
page.getByRole('button', { name: 'submit' });
```
### Generate locators
@ -129,9 +132,11 @@ You can also use the [VS Code Extension](./getting-started-vscode.md) to generat
Assertions are a way to verify that the expected result and the actual result matched or not. By using [web first assertions](./test-assertions.md) Playwright will wait until the expected condition is met. For example, when testing an alert message, a test would click a button that makes a message appear and check that the alert message is there. If the alert message takes half a second to appear, assertions such as `toBeVisible()` will wait and retry if needed.
```js
👍 await expect(page.getByText('welcome')).toBeVisible();
// 👍
await expect(page.getByText('welcome')).toBeVisible();
👎 expect(await page.getByText('welcome').isVisible()).toBe(true);
// 👎
expect(await page.getByText('welcome').isVisible()).toBe(true);
```
#### Don't use manual assertions
@ -139,13 +144,15 @@ Assertions are a way to verify that the expected result and the actual result ma
Don't use manual assertions that are not awaiting the expect. In the code below the await is inside the expect rather than before it. When using assertions such as `isVisible()` the test won't wait a single second, it will just check the locator is there and return immediately.
```js
👎 expect(await page.getByText('welcome').isVisible()).toBe(true);
// 👎
expect(await page.getByText('welcome').isVisible()).toBe(true);
```
Use web first assertions such as `toBeVisible()` instead.
```js
👍 await expect(page.getByText('welcome')).toBeVisible();
// 👍
await expect(page.getByText('welcome')).toBeVisible();
```
### Configure debugging
@ -162,7 +169,7 @@ You can live debug your test by clicking or editing the locators in your test in
You can also debug your tests with the Playwright inspector by running your tests with the `--debug` flag.
```js
```bash
npx playwright test --debug
```
@ -174,7 +181,7 @@ You can then step through your test, view actionability logs and edit the locato
To debug a specific test add the name of the test file and the line number of the test followed by the `--debug` flag.
```js
```bash
npx playwright test example.spec.ts:9 --debug
```
#### Debugging on CI
@ -185,12 +192,12 @@ For CI failures, use the Playwright [trace viewer](./trace-viewer.md) instead of
Traces are configured in the Playwright config file and are set to run on CI on the first retry of a failed test. We don't recommend setting this to `on` so that traces are run on every test as it's very performance heavy. However you can run a trace locally when developing with the `--trace` flag.
```js
```bash
npx playwright test --trace on
```
Once you run this command your traces will be recorded for each test and can be viewed directly from the HTML report.
```js
```bash
npx playwright show-report
````
@ -237,14 +244,14 @@ export default defineConfig({
By keeping your Playwright version up to date you will be able to test your app on the latest browser versions and catch failures before the latest browser version is released to the public.
```js
```bash
npm install -D @playwright/test@latest
```
Check the [release notes](./release-notes.md) to see what the latest version is and what changes have been released.
You can see what version of Playwright you have by running the following command.
```js
```bash
npx playwright --version
```
@ -273,7 +280,7 @@ test('runs in parallel 2', async ({ page }) => { /* ... */ });
Playwright can [shard](./test-parallel.md#shard-tests-between-multiple-machines) a test suite, so that it can be executed on multiple machines.
```js
```bash
npx playwright test --shard=1/3
```

View File

@ -611,7 +611,11 @@ steps:
```
Note: The JUnit reporter needs to be configured accordingly via
```js
["junit", { outputFile: "test-results/e2e-junit-results.xml" }]
import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: ['junit', { outputFile: 'test-results/e2e-junit-results.xml' }],
});
```
in `playwright.config.ts`.

View File

@ -163,7 +163,7 @@ await page.GotoAsync("https://www.openstreetmap.org/");
If a certain event needs to be handled once, there is a convenience API for that:
```js
page.once('dialog', dialog => dialog.accept("2021"));
page.once('dialog', dialog => dialog.accept('2021'));
await page.evaluate("prompt('Enter a number:')");
```

View File

@ -88,7 +88,7 @@ Using [`method: Locator.setChecked`] is the easiest way to check and uncheck a c
await page.getByLabel('I agree to the terms above').check();
// Assert the checked state
expect(await page.getByLabel('Subscribe to newsletter').isChecked()).toBeTruthy()
expect(await page.getByLabel('Subscribe to newsletter').isChecked()).toBeTruthy();
// Select the radio button
await page.getByLabel('XL').check();

View File

@ -33,7 +33,7 @@ import assert from 'node:assert';
// Teardown
await context.close();
await browser.close();
})()
})();
```
```js tab=js-js
@ -55,7 +55,7 @@ const { chromium, devices } = require('playwright');
// Teardown
await context.close();
await browser.close();
})()
})();
```
Run it with `node my-script.js`.

View File

@ -112,7 +112,7 @@ DOM changes in between the calls due to re-render, the new element corresponding
locator will be used.
```js
const locator = page.getByRole('button', { name: 'Sign in' })
const locator = page.getByRole('button', { name: 'Sign in' });
await locator.hover();
await locator.click();
@ -316,8 +316,8 @@ You can fill the input after locating it by the placeholder text:
```js
await page
.getByPlaceholder("name@example.com")
.fill("playwright@microsoft.com");
.getByPlaceholder('name@example.com')
.fill('playwright@microsoft.com');
```
```java
@ -934,7 +934,7 @@ await page
.getByRole('listitem')
.filter({ has: page.getByRole('heading', { name: 'Product 2' }) })
.getByRole('button', { name: 'Add to cart' })
.click()
.click();
```
```java

View File

@ -130,7 +130,7 @@ test('update battery status (no golden)', async ({ page }) => {
this.charging = value;
this._chargingListeners.forEach(cb => cb());
}
};
}
const mockBattery = new BatteryMock();
// Override the method to always return mock battery info.
window.navigator.getBattery = async () => mockBattery;

View File

@ -194,7 +194,7 @@ const browser = await chromium.launch({
});
const context = await browser.newContext({
proxy: { server: 'http://myproxy.com:3128' }
})
});
```
```java
@ -555,8 +555,7 @@ await page.route('**/*.{png,jpg,jpeg}', route => route.abort());
// Abort based on the request type
await page.route('**/*', route => {
return route.request().resourceType() === 'image' ?
route.abort() : route.continue();
return route.request().resourceType() === 'image' ? route.abort() : route.continue();
});
```

View File

@ -903,7 +903,7 @@ is equivalent to
document
.querySelector('article')
.querySelector('.bar > .baz')
.querySelector('span[attr=value]')
.querySelector('span[attr=value]');
```
If a selector needs to include `>>` in the body, it should be escaped inside a string to not be confused with chaining separator, e.g. `text="some >> text"`.

View File

@ -195,7 +195,7 @@ If the action that triggers the new page is unknown, the following pattern can b
context.on('page', async page => {
await page.waitForLoadState();
console.log(await page.title());
})
});
```
```java
@ -295,7 +295,7 @@ If the action that triggers the popup is unknown, the following pattern can be u
page.on('popup', async popup => {
await popup.waitForLoadState();
console.log(await popup.title());
})
});
```
```java

View File

@ -42,11 +42,11 @@ exports.PlaywrightDevPage = class PlaywrightDevPage {
await this.getStarted();
await this.pomLink.click();
}
}
};
```
```js tab=js-ts title="playwright-dev-page.ts"
import { expect, Locator, Page } from '@playwright/test';
import { expect, type Locator, type Page } from '@playwright/test';
export class PlaywrightDevPage {
readonly page: Page;

View File

@ -39,13 +39,13 @@ describe('angularjs homepage todo list', function() {
element(by.model('todoList.todoText')).sendKeys('first test');
element(by.css('[value="add"]')).click();
var todoList = element.all(by.repeater('todo in todoList.todos'));
const todoList = element.all(by.repeater('todo in todoList.todos'));
expect(todoList.count()).toEqual(3);
expect(todoList.get(2).getText()).toEqual('first test');
// You wrote your first test, cross it off the list
todoList.get(2).element(by.css('input')).click();
var completedAmount = element.all(by.css('.done-true'));
const completedAmount = element.all(by.css('.done-true'));
expect(completedAmount.count()).toEqual(2);
});
});
@ -57,14 +57,14 @@ Line-by-line migration to Playwright Test:
```js
const { test, expect } = require('@playwright/test'); // 1
test.describe('angularjs homepage todo list', function() {
test('should add a todo', async function({page}) { // 2, 3
test.describe('angularjs homepage todo list', () => {
test('should add a todo', async ({ page }) => { // 2, 3
await page.goto('https://angularjs.org'); // 4
await page.locator('[ng-model="todoList.todoText"]').fill('first test');
await page.locator('[value="add"]').click();
var todoList = page.locator('[ng-repeat="todo in todoList.todos"]'); // 5
const todoList = page.locator('[ng-repeat="todo in todoList.todos"]'); // 5
await expect(todoList).toHaveCount(3);
await expect(todoList.nth(2)).toHaveText('first test', {
useInnerText: true,
@ -72,10 +72,10 @@ test.describe('angularjs homepage todo list', function() {
// You wrote your first test, cross it off the list
await todoList.nth(2).getByRole('textbox').click();
var completedAmount = page.locator('.done-true');
const completedAmount = page.locator('.done-true');
await expect(completedAmount).toHaveCount(2);
});
}
});
```
Migration highlights (see inline comments in the Playwright Test code snippet):
@ -127,7 +127,7 @@ Here's how to polyfill `waitForAngular` function in Playwright Test:
await Promise.all(window.getAllAngularTestabilities().map(whenStable));
// @ts-expect-error
async function whenStable(testability) {
return new Promise((res) => testability.whenStable(res) );
return new Promise(res => testability.whenStable(res));
}
}
});

View File

@ -111,7 +111,7 @@ describe('Playwright homepage', () => {
it('contains hero title', async () => {
await page.goto('https://playwright.dev/');
await page.waitForSelector('.hero__title');
const text = await page.$eval('.hero__title', (e) => e.textContent);
const text = await page.$eval('.hero__title', e => e.textContent);
expect(text).toContain('Playwright enables reliable end-to-end testing'); // 5
});

View File

@ -589,7 +589,11 @@ All the same methods are also available on [Locator], [FrameLocator] and [Frame]
- New options `host` and `port` for the html reporter.
```js
reporters: [['html', { host: 'localhost', port: '9223' }]]
import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: [['html', { host: 'localhost', port: '9223' }]],
});
```
- New field `FullConfig.configFile` is available to test reporters, specifying the path to the config file if any.
@ -1001,7 +1005,7 @@ WebServer is now considered "ready" if request to the specified url has any of t
```js
// Click a button with accessible name "log in"
await page.locator('role=button[name="log in"]').click()
await page.locator('role=button[name="log in"]').click();
```
Read more in [our documentation](./locators.md#locate-by-role).
@ -1044,7 +1048,7 @@ WebServer is now considered "ready" if request to the specified url has any of t
```js
// Click a button with accessible name "log in"
await page.locator('role=button[name="log in"]').click()
await page.locator('role=button[name="log in"]').click();
```
Read more in [our documentation](./locators.md#locate-by-role).

View File

@ -128,14 +128,14 @@ Additionally, any network request made by the **Page** (including its sub-[Frame
Many Service Worker implementations simply execute the request from the page (possibly with some custom caching/offline logic omitted for simplicity):
```js title="transparent-service-worker.js"
self.addEventListener("fetch", (event) => {
self.addEventListener('fetch', event => {
// actually make the request
const responsePromise = fetch(event.request);
// send it back to the page
event.respondWith(responsePromise);
});
self.addEventListener("activate", (event) => {
self.addEventListener('activate', (event) => {
event.waitUntil(clients.claim());
});
```
@ -180,17 +180,17 @@ Consider the code snippets below to understand Playwright's view into the Reques
```js title="complex-service-worker.js"
self.addEventListener("install", function (event) {
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open("v1").then(function (cache) {
caches.open('v1').then(function (cache) {
// 1. Pre-fetches and caches /addressbook.json
return cache.add("/addressbook.json");
return cache.add('/addressbook.json');
})
);
});
// Opt to handle FetchEvent's from the page
self.addEventListener("fetch", (event) => {
self.addEventListener('fetch', (event) => {
event.respondWith(
(async () => {
// 1. Try to first serve directly from caches
@ -198,13 +198,13 @@ self.addEventListener("fetch", (event) => {
if (response) return response;
// 2. Re-write request for /foo to /bar
if (event.request.url.endsWith("foo")) return fetch("./bar");
if (event.request.url.endsWith('foo')) return fetch('./bar');
// 3. Prevent tracker.js from being retrieved, and returns a placeholder response
if (event.request.url.endsWith("tracker.js"))
return new Response('console.log("no trackers!")', {
if (event.request.url.endsWith('tracker.js'))
return new Response('console.log('no trackers!')', {
status: 200,
headers: { "Content-Type": "text/javascript" },
headers: { 'Content-Type': 'text/javascript' },
});
// 4. Otherwise, fallthrough, perform the fetch and respond
@ -213,7 +213,7 @@ self.addEventListener("fetch", (event) => {
);
});
self.addEventListener("activate", (event) => {
self.addEventListener('activate', (event) => {
event.waitUntil(clients.claim());
});
```

View File

@ -644,7 +644,7 @@ module.exports = defineConfig({
```js tab=js-ts title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
import { Options } from './my-test';
import type { Options } from './my-test';
export default defineConfig<Options>({
projects: [

View File

@ -57,7 +57,7 @@ of the matchers:
```js
expect(value).not.toEqual(0);
await expect(locator).not.toContainText("some text");
await expect(locator).not.toContainText('some text');
```
## Soft Assertions

View File

@ -378,7 +378,9 @@ import { defineConfig } from '@playwright/experimental-ct-react';
export default defineConfig({
use: {
ctViteConfig: { ... },
ctViteConfig: {
// ...
},
},
});
```
@ -386,7 +388,7 @@ export default defineConfig({
### Q) What's the difference between `@playwright/test` and `@playwright/experimental-ct-{react,svelte,vue,solid}`?
```js
test('…', async { mount, page, context } => {
test('…', async ({ mount, page, context }) => {
// …
});
```

View File

@ -83,7 +83,7 @@ export class TodoPage {
```
```js tab=js-ts title="todo-page.ts"
import { Page, Locator } from '@playwright/test';
import type { Page, Locator } from '@playwright/test';
export class TodoPage {
private readonly inputBox: Locator;
@ -207,7 +207,7 @@ export class TodoPage {
```
```js tab=js-ts title="todo-page.ts"
import { Page, Locator } from '@playwright/test';
import type { Page, Locator } from '@playwright/test';
export class TodoPage {
private readonly inputBox: Locator;
@ -349,7 +349,7 @@ export class TodoPage {
```
```js tab=js-ts title="todo-page.ts"
import { Page, Locator } from '@playwright/test';
import type { Page, Locator } from '@playwright/test';
export class TodoPage {
private readonly inputBox: Locator;
@ -402,7 +402,7 @@ export class SettingsPage {
```
```js tab=js-ts title="settings-page.ts"
import { Page } from '@playwright/test';
import type { Page } from '@playwright/test';
export class SettingsPage {
constructor(public readonly page: Page) {
@ -792,7 +792,7 @@ export class TodoPage {
```
```js tab=js-ts title="todo-page.ts"
import { Page, Locator } from '@playwright/test';
import type { Page, Locator } from '@playwright/test';
export class TodoPage {
private readonly inputBox: Locator;
@ -903,7 +903,7 @@ module.exports = defineConfig({
```js tab=js-ts title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
import { MyOptions } from './my-test';
import type { MyOptions } from './my-test';
export default defineConfig<MyOptions>({
projects: [

View File

@ -71,10 +71,10 @@ export default defineConfig({
},
{
name: 'logged in chromium',
use: { ...devices['Desktop Chrome'] },
testMatch: '**/*.loggedin.spec.ts',
dependencies: ['setup'],
use: {
...devices['Desktop Chrome'],
storageState: STORAGE_STATE,
},
},
@ -115,7 +115,7 @@ test.beforeEach(async ({ page }) => {
test('menu', async ({ page }) => {
// You are signed in!
})
});
```
For a more detailed example check out our blog post: [A better global setup in Playwright reusing login with project dependencies](https://dev.to/playwright/a-better-global-setup-in-playwright-reusing-login-with-project-dependencies-14) or check the [v1.31 release video](https://youtu.be/PI50YAPTAs4) to see the demo.
@ -234,7 +234,7 @@ export default defineConfig({
Here is a global setup example that authenticates once and reuses authentication state in tests. It uses the `baseURL` and `storageState` options from the configuration file.
```js title="global-setup.ts"
import { chromium, FullConfig } from '@playwright/test';
import { chromium, type FullConfig } from '@playwright/test';
async function globalSetup(config: FullConfig) {
const { baseURL, storageState } = config.projects[0].use;
@ -278,7 +278,7 @@ test('test', async ({ page }) => {
You can make arbitrary data available in your tests from your global setup file by setting them as environment variables via `process.env`.
```js title="global-setup.ts"
import { FullConfig } from '@playwright/test';
import type { FullConfig } from '@playwright/test';
async function globalSetup(config: FullConfig) {
process.env.FOO = 'some data';
@ -311,7 +311,7 @@ test('test', async ({ page }) => {
In some instances, it may be useful to capture a trace of failures encountered during the global setup. In order to do this, you must [start tracing](./api/class-tracing.md#tracing-start) in your setup, and you must ensure that you [stop tracing](./api/class-tracing.md#tracing-stop) if an error occurs before that error is thrown. This can be achieved by wrapping your setup in a `try...catch` block. Here is an example that expands the global setup example to capture a trace.
```js title="global-setup.ts"
import { chromium, FullConfig } from '@playwright/test';
import { chromium, type FullConfig } from '@playwright/test';
async function globalSetup(config: FullConfig) {
const { baseURL, storageState } = config.projects[0].use;

View File

@ -99,7 +99,7 @@ Using serial is not recommended. It is usually better to make your tests isolate
:::
```js
import { test, Page } from '@playwright/test';
import { test, type Page } from '@playwright/test';
// Annotate entire file as serial.
test.describe.configure({ mode: 'serial' });

View File

@ -36,7 +36,7 @@ module.exports = MyReporter;
```
```js tab=js-ts title="my-awesome-reporter.ts"
import { Reporter, FullConfig, Suite, TestCase, TestResult, FullResult } from '@playwright/test/reporter';
import type { Reporter, FullConfig, Suite, TestCase, TestResult, FullResult } from '@playwright/test/reporter';
class MyReporter implements Reporter {
constructor(options: { customOption?: string } = {}) {

View File

@ -289,7 +289,7 @@ export default defineConfig({
You can create a custom reporter by implementing a class with some of the reporter methods. Learn more about the [Reporter] API.
```js title="my-awesome-reporter.ts"
import { FullConfig, FullResult, Reporter, Suite, TestCase, TestResult } from '@playwright/test/reporter';
import type { FullConfig, FullResult, Reporter, Suite, TestCase, TestResult } from '@playwright/test/reporter';
class MyReporter implements Reporter {
onBegin(config: FullConfig, suite: Suite) {

View File

@ -191,7 +191,7 @@ test('runs second', async () => {
```
```js tab=js-ts title="example.spec.ts"
import { test, Page } from '@playwright/test';
import { test, type Page } from '@playwright/test';
test.describe.configure({ mode: 'serial' });

View File

@ -15,7 +15,7 @@ import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: 'http://127.0.0.1:3000'
baseURL: 'http://127.0.0.1:3000',
// Populates context with given storage state.
storageState: 'state.json',
@ -133,7 +133,7 @@ import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Capture screenshot after each test failure.
screenshot: 'only-on-failure'
screenshot: 'only-on-failure',
// Record trace only when retrying a test for the first time.
trace: 'on-first-retry',
@ -224,11 +224,9 @@ export default defineConfig({
An example test illustrating the initial context options are set:
```js
import { test, expect } from "@playwright/test";
import { test, expect } from '@playwright/test';
test('should inherit use options on context when using built-in browser fixture', async ({
browser,
}) => {
test('should inherit use options on context when using built-in browser fixture', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
expect(await page.evaluate(() => navigator.userAgent)).toBe('some custom ua');
@ -263,7 +261,7 @@ export default defineConfig({
name: 'chromium',
use: {
...devices['Desktop Chrome'],
locale: 'de-DE'
locale: 'de-DE',
},
},
],
@ -289,7 +287,7 @@ import { test, expect } from '@playwright/test';
test.describe('french language block', () => {
test.use({ { locale: 'fr-FR' }});
test.use({ locale: 'fr-FR' });
test('example', async ({ page }) => {
// ...

View File

@ -92,13 +92,13 @@ Playwright includes [assertions](./test-assertions) that automatically wait for
```js
// Testing Library
await waitFor(() => {
expect(getByText('the lion king')).toBeInTheDocument()
})
await waitForElementToBeRemoved(() => queryByText('the mummy'))
expect(getByText('the lion king')).toBeInTheDocument();
});
await waitForElementToBeRemoved(() => queryByText('the mummy'));
// Playwright
await expect(page.getByText('the lion king')).toBeVisible()
await expect(page.getByText('the mummy')).toBeHidden()
await expect(page.getByText('the lion king')).toBeVisible();
await expect(page.getByText('the mummy')).toBeHidden();
```
When you cannot find a suitable assertion, use [`expect.poll`](./test-assertions#polling) instead.
@ -116,12 +116,12 @@ You can create a locator inside another locator with [`method: Locator.locator`]
```js
// Testing Library
const messages = document.getElementById('messages')
const helloMessage = within(messages).getByText('hello')
const messages = document.getElementById('messages');
const helloMessage = within(messages).getByText('hello');
// Playwright
const messages = component.locator('id=messages')
const helloMessage = messages.getByText('hello')
const messages = component.locator('id=messages');
const helloMessage = messages.getByText('hello');
```
## Playwright Test Super Powers

View File

@ -25,7 +25,7 @@ By default the [playwright.config](/test-configuration.md#record-test-trace) fil
import { defineConfig } from '@playwright/test';
export default defineConfig({
retries: process.env.CI ? 2 : 0, // set to 2 when running on CI
...
// ...
use: {
trace: 'on-first-retry', // record traces on first retry of each test
},

View File

@ -96,7 +96,7 @@ export const test = base.extend({
}));
const browser = await playwright.chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`);
await use(browser);
await browser.close()
await browser.close();
childProcess.execSync(`taskkill /pid ${webView2Process.pid} /T /F`);
fs.rmdirSync(userDataDir, { recursive: true });
},

View File

@ -154,7 +154,8 @@ Playwright Test is based on the concept of [test fixtures](./test-fixtures.md) s
```js title="tests/example.spec.ts"
test('basic test', async ({ page }) => {
...
// ...
});
```
### Using Test Hooks
@ -162,17 +163,17 @@ test('basic test', async ({ page }) => {
You can use various [test hooks](./api/class-test.md) such as `test.describe` to declare a group of tests and `test.beforeEach` and `test.afterEach` which are executed before/after each test. Other hooks include the `test.beforeAll` and `test.afterAll` which are executed once per worker before/after all tests.
```js title="tests/example.spec.ts"
import { test, expect } from "@playwright/test";
import { test, expect } from '@playwright/test';
test.describe("navigation", () => {
test.describe('navigation', () => {
test.beforeEach(async ({ page }) => {
// Go to the starting url before each test.
await page.goto("https://playwright.dev/");
await page.goto('https://playwright.dev/');
});
test("main navigation", async ({ page }) => {
test('main navigation', async ({ page }) => {
// Assertions use the expect API.
await expect(page).toHaveURL("https://playwright.dev/");
await expect(page).toHaveURL('https://playwright.dev/');
});
});
```

View File

@ -112,7 +112,7 @@ export interface Page {
*
* ```js
* const bodyHandle = await page.evaluate('document.body');
* const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
* const html = await page.evaluate<string, HTMLElement>(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
* await bodyHandle.dispose();
* ```
*
@ -159,7 +159,7 @@ export interface Page {
*
* ```js
* const bodyHandle = await page.evaluate('document.body');
* const html = await page.evaluate(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
* const html = await page.evaluate<string, HTMLElement>(([body, suffix]) => body.innerHTML + suffix, [bodyHandle, 'hello']);
* await bodyHandle.dispose();
* ```
*
@ -186,8 +186,8 @@ export interface Page {
* **Usage**
*
* ```js
* // Handle for the window object.
* const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window));
* aWindowHandle; // Handle for the window object.
* ```
*
* A string can also be passed in instead of a function:
@ -228,8 +228,8 @@ export interface Page {
* **Usage**
*
* ```js
* // Handle for the window object.
* const aWindowHandle = await page.evaluateHandle(() => Promise.resolve(window));
* aWindowHandle; // Handle for the window object.
* ```
*
* A string can also be passed in instead of a function:
@ -641,7 +641,7 @@ export interface Page {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -679,7 +679,7 @@ export interface Page {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -717,7 +717,7 @@ export interface Page {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -755,7 +755,7 @@ export interface Page {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -977,7 +977,7 @@ export interface Page {
* that can be uploaded after that.
*
* ```js
* page.on('filechooser', async (fileChooser) => {
* page.on('filechooser', async fileChooser => {
* await fileChooser.setFiles('/tmp/myfile.pdf');
* });
* ```
@ -1273,7 +1273,7 @@ export interface Page {
* that can be uploaded after that.
*
* ```js
* page.on('filechooser', async (fileChooser) => {
* page.on('filechooser', async fileChooser => {
* await fileChooser.setFiles('/tmp/myfile.pdf');
* });
* ```
@ -1664,7 +1664,7 @@ export interface Page {
* that can be uploaded after that.
*
* ```js
* page.on('filechooser', async (fileChooser) => {
* page.on('filechooser', async fileChooser => {
* await fileChooser.setFiles('/tmp/myfile.pdf');
* });
* ```
@ -2557,8 +2557,8 @@ export interface Page {
*
* ```js
* await page
* .getByPlaceholder("name@example.com")
* .fill("playwright@microsoft.com");
* .getByPlaceholder('name@example.com')
* .fill('playwright@microsoft.com');
* ```
*
* @param text Text to locate the element for.
@ -2705,9 +2705,13 @@ export interface Page {
*
* ```js
* // Set custom test id attribute from @playwright/test config:
* import { defineConfig } from '@playwright/test';
*
* export default defineConfig({
* use: {
* testIdAttribute: 'data-pw'
* }
* },
* });
* ```
*
* @param testId Id to locate the element by.
@ -2733,19 +2737,19 @@ export interface Page {
*
* ```js
* // Matches <span>
* page.getByText('world')
* page.getByText('world');
*
* // Matches first <div>
* page.getByText('Hello world')
* page.getByText('Hello world');
*
* // Matches second <div>
* page.getByText('Hello', { exact: true })
* page.getByText('Hello', { exact: true });
*
* // Matches both <div>s
* page.getByText(/Hello/)
* page.getByText(/Hello/);
*
* // Matches second <div>
* page.getByText(/^hello$/i)
* page.getByText(/^hello$/i);
* ```
*
* **Details**
@ -4321,7 +4325,7 @@ export interface Page {
* that can be uploaded after that.
*
* ```js
* page.on('filechooser', async (fileChooser) => {
* page.on('filechooser', async fileChooser => {
* await fileChooser.setFiles('/tmp/myfile.pdf');
* });
* ```
@ -4719,10 +4723,9 @@ export interface Page {
*
* function dumpFrameTree(frame, indent) {
* console.log(indent + frame.url());
* for (const child of frame.childFrames()) {
* for (const child of frame.childFrames())
* dumpFrameTree(child, indent + ' ');
* }
* }
* })();
* ```
*
@ -4833,8 +4836,8 @@ export interface Frame {
* **Usage**
*
* ```js
* // Handle for the window object
* const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
* aWindowHandle; // Handle for the window object.
* ```
*
* A string can also be passed in instead of a function.
@ -4875,8 +4878,8 @@ export interface Frame {
* **Usage**
*
* ```js
* // Handle for the window object
* const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));
* aWindowHandle; // Handle for the window object.
* ```
*
* A string can also be passed in instead of a function.
@ -5270,7 +5273,7 @@ export interface Frame {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.mainFrame().waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -5308,7 +5311,7 @@ export interface Frame {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.mainFrame().waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -5346,7 +5349,7 @@ export interface Frame {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.mainFrame().waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -5384,7 +5387,7 @@ export interface Frame {
* (async () => {
* const browser = await chromium.launch();
* const page = await browser.newPage();
* for (let currentURL of ['https://google.com', 'https://bbc.com']) {
* for (const currentURL of ['https://google.com', 'https://bbc.com']) {
* await page.goto(currentURL);
* const element = await page.mainFrame().waitForSelector('img');
* console.log('Loaded image: ' + await element.getAttribute('src'));
@ -6019,8 +6022,8 @@ export interface Frame {
*
* ```js
* await page
* .getByPlaceholder("name@example.com")
* .fill("playwright@microsoft.com");
* .getByPlaceholder('name@example.com')
* .fill('playwright@microsoft.com');
* ```
*
* @param text Text to locate the element for.
@ -6167,9 +6170,13 @@ export interface Frame {
*
* ```js
* // Set custom test id attribute from @playwright/test config:
* import { defineConfig } from '@playwright/test';
*
* export default defineConfig({
* use: {
* testIdAttribute: 'data-pw'
* }
* },
* });
* ```
*
* @param testId Id to locate the element by.
@ -6195,19 +6202,19 @@ export interface Frame {
*
* ```js
* // Matches <span>
* page.getByText('world')
* page.getByText('world');
*
* // Matches first <div>
* page.getByText('Hello world')
* page.getByText('Hello world');
*
* // Matches second <div>
* page.getByText('Hello', { exact: true })
* page.getByText('Hello', { exact: true });
*
* // Matches both <div>s
* page.getByText(/Hello/)
* page.getByText(/Hello/);
*
* // Matches second <div>
* page.getByText(/^hello$/i)
* page.getByText(/^hello$/i);
* ```
*
* **Details**
@ -11241,8 +11248,8 @@ export interface Locator {
*
* ```js
* await page
* .getByPlaceholder("name@example.com")
* .fill("playwright@microsoft.com");
* .getByPlaceholder('name@example.com')
* .fill('playwright@microsoft.com');
* ```
*
* @param text Text to locate the element for.
@ -11389,9 +11396,13 @@ export interface Locator {
*
* ```js
* // Set custom test id attribute from @playwright/test config:
* import { defineConfig } from '@playwright/test';
*
* export default defineConfig({
* use: {
* testIdAttribute: 'data-pw'
* }
* },
* });
* ```
*
* @param testId Id to locate the element by.
@ -11417,19 +11428,19 @@ export interface Locator {
*
* ```js
* // Matches <span>
* page.getByText('world')
* page.getByText('world');
*
* // Matches first <div>
* page.getByText('Hello world')
* page.getByText('Hello world');
*
* // Matches second <div>
* page.getByText('Hello', { exact: true })
* page.getByText('Hello', { exact: true });
*
* // Matches both <div>s
* page.getByText(/Hello/)
* page.getByText(/Hello/);
*
* // Matches second <div>
* page.getByText(/^hello$/i)
* page.getByText(/^hello$/i);
* ```
*
* **Details**
@ -13204,12 +13215,12 @@ export namespace errors {
* const context = await browser.newContext();
* const page = await context.newPage();
* try {
* await page.locator("text=Foo").click({
* await page.locator('text=Foo').click({
* timeout: 100,
* })
* });
* } catch (error) {
* if (error instanceof playwright.errors.TimeoutError)
* console.log("Timeout!")
* console.log('Timeout!');
* }
* await browser.close();
* })();
@ -16409,7 +16420,7 @@ export interface BrowserServer {
*
* ```js
* // Listen for all console logs
* page.on('console', msg => console.log(msg.text()))
* page.on('console', msg => console.log(msg.text()));
*
* // Listen for all console events and handle errors
* page.on('console', msg => {
@ -16425,8 +16436,8 @@ export interface BrowserServer {
* const msg = await msgPromise;
*
* // Deconstruct console log arguments
* await msg.args()[0].jsonValue() // hello
* await msg.args()[1].jsonValue() // 42
* await msg.args()[0].jsonValue(); // hello
* await msg.args()[1].jsonValue(); // 42
* ```
*
*/
@ -17188,8 +17199,8 @@ export interface FrameLocator {
*
* ```js
* await page
* .getByPlaceholder("name@example.com")
* .fill("playwright@microsoft.com");
* .getByPlaceholder('name@example.com')
* .fill('playwright@microsoft.com');
* ```
*
* @param text Text to locate the element for.
@ -17336,9 +17347,13 @@ export interface FrameLocator {
*
* ```js
* // Set custom test id attribute from @playwright/test config:
* import { defineConfig } from '@playwright/test';
*
* export default defineConfig({
* use: {
* testIdAttribute: 'data-pw'
* }
* },
* });
* ```
*
* @param testId Id to locate the element by.
@ -17364,19 +17379,19 @@ export interface FrameLocator {
*
* ```js
* // Matches <span>
* page.getByText('world')
* page.getByText('world');
*
* // Matches first <div>
* page.getByText('Hello world')
* page.getByText('Hello world');
*
* // Matches second <div>
* page.getByText('Hello', { exact: true })
* page.getByText('Hello', { exact: true });
*
* // Matches both <div>s
* page.getByText(/Hello/)
* page.getByText(/Hello/);
*
* // Matches second <div>
* page.getByText(/^hello$/i)
* page.getByText(/^hello$/i);
* ```
*
* **Details**
@ -17663,7 +17678,7 @@ export interface Keyboard {
* log: (name, severity, message, args) => console.log(`${name} ${message}`)
* }
* });
* ...
* // ...
* })();
* ```
*

View File

@ -3322,7 +3322,7 @@ export interface TestType<TestArgs extends KeyValue, WorkerArgs extends KeyValue
* ```js
* // playwright.config.ts
* import { defineConfig } from '@playwright/test';
* import { Options } from './my-test';
* import type { Options } from './my-test';
*
* export default defineConfig<Options>({
* projects: [
@ -5573,8 +5573,8 @@ interface LocatorAssertions {
* ```
*
* ```js
* const locator = page.locator("id=favorite-colors");
* await locator.selectOption(["R", "G"]);
* const locator = page.locator('id=favorite-colors');
* await locator.selectOption(['R', 'G']);
* await expect(locator).toHaveValues([/R/, /G/]);
* ```
*

View File

@ -316,7 +316,7 @@ export interface FullResult {
*
* ```js
* // my-awesome-reporter.ts
* import { Reporter, FullConfig, Suite, TestCase, TestResult, FullResult } from '@playwright/test/reporter';
* import type { Reporter, FullConfig, Suite, TestCase, TestResult, FullResult } from '@playwright/test/reporter';
*
* class MyReporter implements Reporter {
* constructor(options: { customOption?: string } = {}) {