docs: Update typescript code blocks in docs (#35219)

This commit is contained in:
Chris 2025-03-26 15:29:02 +01:00 committed by GitHub
parent ef5e166fa8
commit 97a542c334
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 44 additions and 48 deletions

View File

@ -244,7 +244,7 @@ type AxeFixture = {
// This new "test" can be used in multiple test files, and each of them will get
// a consistently configured AxeBuilder instance.
export const test = base.extend<AxeFixture>({
makeAxeBuilder: async ({ page }, use, testInfo) => {
makeAxeBuilder: async ({ page }, use) => {
const makeAxeBuilder = () => new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.exclude('#commonly-reused-element-with-known-issue');
@ -255,8 +255,7 @@ export const test = base.extend<AxeFixture>({
export { expect } from '@playwright/test';
```
```js tab=js-js
// axe-test.js
```js tab=js-js title="axe-test.js"
const base = require('@playwright/test');
const AxeBuilder = require('@axe-core/playwright').default;
@ -265,7 +264,7 @@ const AxeBuilder = require('@axe-core/playwright').default;
// This new "test" can be used in multiple test files, and each of them will get
// a consistently configured AxeBuilder instance.
exports.test = base.test.extend({
makeAxeBuilder: async ({ page }, use, testInfo) => {
makeAxeBuilder: async ({ page }, use) => {
const makeAxeBuilder = () => new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.exclude('#commonly-reused-element-with-known-issue');

View File

@ -258,7 +258,7 @@ test('last created issue should be on the server', async ({ page }) => {
await page.getByRole('textbox', { name: 'Title' }).fill('Bug report 1');
await page.getByRole('textbox', { name: 'Comment body' }).fill('Bug description');
await page.getByText('Submit new issue').click();
const issueId = page.url().substr(page.url().lastIndexOf('/'));
const issueId = new URL(page.url()).pathname.split('/').pop();
const newIssue = await apiContext.get(
`https://api.github.com/repos/${USER}/${REPO}/issues/${issueId}`

View File

@ -334,7 +334,7 @@ The way source code is updated can be changed using the `--update-source-method`
- **"overwrite"**: Overwrites the source code with the new snapshot values.
```bash
npx playwright test --update-snapshots --update-source-mode=3way
npx playwright test --update-snapshots --update-source-method=3way
```
#### Snapshots as separate files

View File

@ -18,9 +18,6 @@ Using a canary release in production might seem risky, but in practice, it's not
A canary release passes all automated tests and is used to test e.g. the HTML report, Trace Viewer, or Playwright Inspector with end-to-end tests.
:::
```txt
npm install -D @playwright/test@next
```
## Next npm Dist Tag
@ -34,7 +31,7 @@ You can see on [npm](https://www.npmjs.com/package/@playwright/test?activeTab=ve
## Using a Canary Release
```txt
```bash
npm install -D @playwright/test@next
```

View File

@ -5,7 +5,7 @@ title: "Page object models"
## Introduction
Large test suites can be structured to optimize ease of authoring and maintenance. Page object models are one such approach to structure your test suite.
Large test suites can be structured to optimize ease of authoring and maintenance. Page object models are one such approach to structure your test suite.
A page object represents a part of your web application. An e-commerce web application might have a home page, a listings page and a checkout page. Each of them can be represented by page object models.

View File

@ -333,7 +333,7 @@ npx playwright test --tsconfig tsconfig.test.json
You can now pass [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) and `string` as query parameters to [APIRequestContext]:
```ts
```js
test('query params', async ({ request }) => {
const searchParams = new URLSearchParams();
searchParams.set('userId', 1);
@ -382,7 +382,7 @@ Playwright now allows you to supply client-side certificates, so that server can
The following snippet sets up a client certificate for `https://example.com`:
```ts
```js
import { defineConfig } from '@playwright/test';
export default defineConfig({
@ -423,7 +423,7 @@ There are two ways to use the router fixture:
Here is an example of reusing your existing MSW handlers in the test.
```ts
```js
import { handlers } from '@src/mocks/handlers';
test.beforeEach(async ({ router }) => {
@ -516,7 +516,7 @@ See [the clock guide](./clock.md) for more details.
- New options [`property: TestConfig.respectGitIgnore`] and [`property: TestProject.respectGitIgnore`] control whether files matching `.gitignore` patterns are excluded when searching for tests.
- New property `timeout` is now available for custom expect matchers. This property takes into account `playwright.config.ts` and `expect.configure()`.
```ts
```js
import { expect as baseExpect } from '@playwright/test';
export const expect = baseExpect.extend({
@ -531,12 +531,12 @@ See [the clock guide](./clock.md) for more details.
### Miscellaneous
- Method [`method: Locator.setInputFiles`] now supports uploading a directory for `<input type=file webkitdirectory>` elements.
```ts
```js
await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir'));
```
- Multiple methods like [`method: Locator.click`] or [`method: Locator.press`] now support a `ControlOrMeta` modifier key. This key maps to `Meta` on macOS and maps to `Control` on Windows and Linux.
```ts
```js
// Press the common keyboard shortcut Control+S or Meta+S to trigger a "Save" operation.
await page.keyboard.press('ControlOrMeta+S');
```
@ -1845,7 +1845,7 @@ This version was also tested against the following stable channels:
* [`method: Test.step`] now returns the value of the step function:
```ts
```js
test('should work', async ({ page }) => {
const pageTitle = await test.step('get title', async () => {
await page.goto('https://playwright.dev');
@ -1889,7 +1889,7 @@ This version was also tested against the following stable channels:
Launch multiple web servers, databases, or other processes by passing an array of configurations:
```ts title="playwright.config.ts"
```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: [
@ -1929,7 +1929,7 @@ Linux support looks like this:
It is now possible to call [`method: Test.describe`] to create suites without a title. This is useful for giving a group of tests a common option with [`method: Test.use`].
```ts
```js
test.describe(() => {
test.use({ colorScheme: 'dark' });
@ -2020,7 +2020,7 @@ npx playwright open --save-har=github.har.zip https://github.com/microsoft
Alternatively, you can record HAR programmatically:
```ts
```js
const context = await browser.newContext({
recordHar: { path: 'github.har.zip' }
});
@ -2031,7 +2031,7 @@ await context.close();
Use the new methods [`method: Page.routeFromHAR`] or [`method: BrowserContext.routeFromHAR`] to serve matching responses from the [HAR](http://www.softwareishard.com/blog/har-12-spec/) file:
```ts
```js
await context.routeFromHAR('github.har.zip');
```
@ -2044,7 +2044,7 @@ You can now use [`method: Route.fallback`] to defer routing to other handlers.
Consider the following example:
```ts
```js
// Remove a header from all requests.
test.beforeEach(async ({ page }) => {
await page.route('**/*', async route => {
@ -2081,7 +2081,7 @@ Read more about [component testing with Playwright](./test-components).
### Miscellaneous
* If there's a service worker that's in your way, you can now easily disable it with a new context option `serviceWorkers`:
```ts title="playwright.config.ts"
```js title="playwright.config.ts"
export default {
use: {
serviceWorkers: 'block',
@ -2089,7 +2089,7 @@ Read more about [component testing with Playwright](./test-components).
};
```
* Using `.zip` path for `recordHar` context option automatically zips the resulting HAR:
```ts
```js
const context = await browser.newContext({
recordHar: {
path: 'github.har.zip',
@ -2098,7 +2098,7 @@ Read more about [component testing with Playwright](./test-components).
```
* If you intend to edit HAR by hand, consider using the `"minimal"` HAR recording mode
that only records information that is essential for replaying:
```ts
```js
const context = await browser.newContext({
recordHar: {
path: 'github.har',
@ -2136,7 +2136,7 @@ WebServer is now considered "ready" if request to the specified url has any of t
Here is what a typical component test looks like:
```ts title="App.spec.tsx"
```js title="App.spec.tsx"
import { test, expect } from '@playwright/experimental-ct-react';
import App from './App';
@ -2274,7 +2274,7 @@ This version was also tested against the following stable channels:
- Playwright Test now adds [`property: TestConfig.fullyParallel`] mode. By default, Playwright Test parallelizes between files. In fully parallel mode, tests inside a single file are also run in parallel. You can also use `--fully-parallel` command line flag.
```ts title="playwright.config.ts"
```js title="playwright.config.ts"
export default {
fullyParallel: true,
};
@ -2282,7 +2282,7 @@ This version was also tested against the following stable channels:
- [`property: TestProject.grep`] and [`property: TestProject.grepInvert`] are now configurable per project. For example, you can now
configure smoke tests project using `grep`:
```ts title="playwright.config.ts"
```js title="playwright.config.ts"
export default {
projects: [
{
@ -2591,7 +2591,7 @@ Now you can:
To do a request on behalf of Playwright's Page, use **new [`property: Page.request`] API**:
```ts
```js
import { test, expect } from '@playwright/test';
test('context fetch', async ({ page }) => {
@ -2603,7 +2603,7 @@ test('context fetch', async ({ page }) => {
To do a stand-alone request from node.js to an API endpoint, use **new [`request` fixture](./api/class-fixtures#fixtures-request)**:
```ts
```js
import { test, expect } from '@playwright/test';
test('context fetch', async ({ request }) => {
@ -2621,7 +2621,7 @@ It is now possible to do response interception by combining [API Testing](./api-
For example, we can blur all the images on the page:
```ts
```js
import { test, expect } from '@playwright/test';
import jimp from 'jimp'; // image processing library
@ -2667,7 +2667,7 @@ Defaults to the `state: 'visible'`.
Comes especially handy when working with lists:
```ts
```js
import { test, expect } from '@playwright/test';
test('context fetch', async ({ page }) => {
@ -2747,7 +2747,7 @@ Its now possible to emulate the `forced-colors` CSS media feature by passing it
#### 🤝 `test.parallel()` run tests in the same file in parallel
```ts
```js
test.describe.parallel('group', () => {
test('runs in parallel 1', async ({ page }) => {
});
@ -2872,7 +2872,7 @@ List of all new assertions:
Declares a group of tests that should always be run serially. If one of the tests fails, all subsequent tests are skipped. All tests in a group are retried together.
```ts
```js
test.describe.serial('group', () => {
test('runs first', async ({ page }) => { /* ... */ });
test('runs second', async ({ page }) => { /* ... */ });
@ -2885,7 +2885,7 @@ Learn more in the [documentation](./api/class-test#test-describe-serial).
Split long tests into multiple steps using `test.step()` API:
```ts
```js
import { test, expect } from '@playwright/test';
test('test', async ({ page }) => {
@ -2904,7 +2904,7 @@ Step information is exposed in reporters API.
To launch a server during the tests, use the [`webServer`](./test-webserver) option in the configuration file. The server will wait for a given url to be available before running the tests, and the url will be passed over to Playwright as a [`baseURL`](./api/class-testoptions#test-options-base-url) when creating a context.
```ts title="playwright.config.ts"
```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
@ -2988,7 +2988,7 @@ npm i -D @playwright/test
Simple test `tests/foo.spec.ts`:
```ts
```js
import { test, expect } from '@playwright/test';
test('basic test', async ({ page }) => {
@ -3015,7 +3015,7 @@ npx playwright test
Traces are recorded using the new [`property: BrowserContext.tracing`] API:
```ts
```js
const browser = await chromium.launch();
const context = await browser.newContext();

View File

@ -686,7 +686,7 @@ Playwright provides an **experimental** `router` fixture to intercept and handle
Here is an example of reusing your existing MSW handlers in the test.
```ts
```js
import { handlers } from '@src/mocks/handlers';
test.beforeEach(async ({ router }) => {
@ -702,7 +702,7 @@ test('example test', async ({ mount }) => {
You can also introduce a one-off handler for a specific test.
```ts
```js
import { http, HttpResponse } from 'msw';
test('example test', async ({ mount, router }) => {

View File

@ -727,7 +727,7 @@ export const test = base.extend({
[`method: Test.beforeEach`] and [`method: Test.afterEach`] hooks run before/after each test declared in the same file and same [`method: Test.describe`] block (if any). If you want to declare hooks that run before/after each test globally, you can declare them as auto fixtures like this:
```ts title="fixtures.ts"
```js title="fixtures.ts"
import { test as base } from '@playwright/test';
export const test = base.extend<{ forEachTest: void }>({
@ -743,7 +743,7 @@ export const test = base.extend<{ forEachTest: void }>({
And then import the fixtures in all your tests:
```ts title="mytest.spec.ts"
```js title="mytest.spec.ts"
import { test } from './fixtures';
import { expect } from '@playwright/test';
@ -758,7 +758,7 @@ test('basic', async ({ page }) => {
[`method: Test.beforeAll`] and [`method: Test.afterAll`] hooks run before/after all tests declared in the same file and same [`method: Test.describe`] block (if any), once per worker process. If you want to declare hooks
that run before/after all tests in every file, you can declare them as auto fixtures with `scope: 'worker'` as follows:
```ts title="fixtures.ts"
```js title="fixtures.ts"
import { test as base } from '@playwright/test';
export const test = base.extend<{}, { forEachWorker: void }>({
@ -774,7 +774,7 @@ export const test = base.extend<{}, { forEachWorker: void }>({
And then import the fixtures in all your tests:
```ts title="mytest.spec.ts"
```js title="mytest.spec.ts"
import { test } from './fixtures';
import { expect } from '@playwright/test';

View File

@ -51,7 +51,7 @@ In the previous example, each test shard has its own test report. If you want to
Start with adding `blob` reporter to the config when running on CI:
```ts title="playwright.config.ts"
```js title="playwright.config.ts"
export default defineConfig({
testDir: './tests',
reporter: process.env.CI ? 'blob' : 'html',
@ -193,7 +193,7 @@ Supported options:
npx playwright merge-reports --config=merge.config.ts ./blob-reports
```
```ts title="merge.config.ts"
```js title="merge.config.ts"
export default {
testDir: 'e2e',
reporter: [['html', { open: 'never' }]],

View File

@ -657,4 +657,4 @@ with sync_playwright() as p:
page = context.new_page()
test_pinch_in_gesture_to_zoom_out_the_map(page)
browser.close()
```
```