Skip to content

Commit

Permalink
docs(test-parameterize): improve forEach example (#31331)
Browse files Browse the repository at this point in the history
  • Loading branch information
mxschmitt committed Jun 19, 2024
1 parent 6ae9adf commit 9510401
Showing 1 changed file with 54 additions and 6 deletions.
60 changes: 54 additions & 6 deletions docs/src/test-parameterize-js.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9510401

Please sign in to comment.