Skip to content

Commit a11585f

Browse files
committed
cherry-pick(#31331): docs(test-parameterize): improve forEach example
1 parent afcf8d2 commit a11585f

File tree

1 file changed

+54
-6
lines changed

1 file changed

+54
-6
lines changed

docs/src/test-parameterize-js.md

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,61 @@ You can either parameterize tests on a test level or on a project level.
99
## Parameterized Tests
1010

1111
```js title="example.spec.ts"
12-
const people = ['Alice', 'Bob'];
13-
for (const name of people) {
14-
test(`testing with ${name}`, async () => {
15-
// ...
16-
});
12+
[
13+
{ name: 'Alice', expected: 'Hello, Alice!' },
14+
{ name: 'Bob', expected: 'Hello, Bob!' },
15+
{ name: 'Charlie', expected: 'Hello, Charlie!' },
16+
].forEach(({ name, expected }) => {
1717
// You can also do it with test.describe() or with multiple tests as long the test name is unique.
18-
}
18+
test(`testing with ${name}`, async ({ page }) => {
19+
await page.goto(`https://example.com/greet?name=${name}`);
20+
await expect(page.getByRole('heading')).toHaveText(expected);
21+
});
22+
});
23+
```
24+
25+
### Before and after hooks
26+
27+
Most of the time you should put `beforeEach`, `beforeAll`, `afterEach` and `afterAll` hooks outside of `forEach`, so that hooks are executed just once:
28+
29+
```js title="example.spec.ts"
30+
test.beforeEach(async ({ page }) => {
31+
// ...
32+
});
33+
34+
test.afterEach(async ({ page }) => {
35+
// ...
36+
});
37+
38+
[
39+
{ name: 'Alice', expected: 'Hello, Alice!' },
40+
{ name: 'Bob', expected: 'Hello, Bob!' },
41+
{ name: 'Charlie', expected: 'Hello, Charlie!' },
42+
].forEach(({ name, expected }) => {
43+
test(`testing with ${name}`, async ({ page }) => {
44+
await page.goto(`https://example.com/greet?name=${name}`);
45+
await expect(page.getByRole('heading')).toHaveText(expected);
46+
});
47+
});
48+
```
49+
50+
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:
51+
52+
```js title="example.spec.ts"
53+
[
54+
{ name: 'Alice', expected: 'Hello, Alice!' },
55+
{ name: 'Bob', expected: 'Hello, Bob!' },
56+
{ name: 'Charlie', expected: 'Hello, Charlie!' },
57+
].forEach(({ name, expected }) => {
58+
test.describe(() => {
59+
test.beforeEach(async ({ page }) => {
60+
await page.goto(`https://example.com/greet?name=${name}`);
61+
});
62+
test(`testing with ${expected}`, async ({ page }) => {
63+
await expect(page.getByRole('heading')).toHaveText(expected);
64+
});
65+
});
66+
});
1967
```
2068

2169
## Parameterized Projects

0 commit comments

Comments
 (0)