docs(test-parameterize): improve forEach example (#31331)

This commit is contained in:
Max Schmitt 2024-06-19 17:45:27 +02:00 committed by GitHub
parent 6ae9adfa4f
commit 951040185d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -9,13 +9,61 @@ You can either parameterize tests on a test level or on a project level.
## Parameterized Tests
```js title="example.spec.ts"
const people = ['Alice', 'Bob'];
for (const name of people) {
test(`testing with ${name}`, async () => {
// ...
});
[
{ name: 'Alice', expected: 'Hello, Alice!' },
{ name: 'Bob', expected: 'Hello, Bob!' },
{ name: 'Charlie', expected: 'Hello, Charlie!' },
].forEach(({ name, expected }) => {
// You can also do it with test.describe() or with multiple tests as long the test name is unique.
}
test(`testing with ${name}`, async ({ page }) => {
await page.goto(`https://example.com/greet?name=${name}`);
await expect(page.getByRole('heading')).toHaveText(expected);
});
});
```
### Before and after hooks
Most of the time you should put `beforeEach`, `beforeAll`, `afterEach` and `afterAll` hooks outside of `forEach`, so that hooks are executed just once:
```js title="example.spec.ts"
test.beforeEach(async ({ page }) => {
// ...
});
test.afterEach(async ({ page }) => {
// ...
});
[
{ name: 'Alice', expected: 'Hello, Alice!' },
{ name: 'Bob', expected: 'Hello, Bob!' },
{ name: 'Charlie', expected: 'Hello, Charlie!' },
].forEach(({ name, expected }) => {
test(`testing with ${name}`, async ({ page }) => {
await page.goto(`https://example.com/greet?name=${name}`);
await expect(page.getByRole('heading')).toHaveText(expected);
});
});
```
If you want to have hooks for each test, you can put them inside a `describe()` - so they are executed for each iteration / each invidual test:
```js title="example.spec.ts"
[
{ name: 'Alice', expected: 'Hello, Alice!' },
{ name: 'Bob', expected: 'Hello, Bob!' },
{ name: 'Charlie', expected: 'Hello, Charlie!' },
].forEach(({ name, expected }) => {
test.describe(() => {
test.beforeEach(async ({ page }) => {
await page.goto(`https://example.com/greet?name=${name}`);
});
test(`testing with ${expected}`, async ({ page }) => {
await expect(page.getByRole('heading')).toHaveText(expected);
});
});
});
```
## Parameterized Projects