Skip to content

Commit

Permalink
cherry-pick(#23470): docs: improve by adding teardown and examples (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
playwrightmachine authored Jun 9, 2023
1 parent a2798c3 commit 615e2e8
Show file tree
Hide file tree
Showing 2 changed files with 189 additions and 7 deletions.
187 changes: 181 additions & 6 deletions docs/src/test-global-setup-teardown-js.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,26 @@ There are two ways to configure global setup and teardown: using a global setup

[Project dependencies](./api/class-testproject#test-project-dependencies) are a list of projects that need to run before the tests in another project run. They can be useful for configuring the global setup actions so that one project depends on this running first. Using dependencies allows global setup to produce traces and other artifacts.

In this example the chromium, firefox and webkit projects depend on the setup project.
### Setup

First we add a new project with the name 'setup'. We then give it a [`property: TestProject.testMatch`] property in order to match the file called `global.setup.ts`:

```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /global.setup\.ts/,
},
// {
// other project
// }
]
});
```
Then we add the [`property: TestProject.dependencies`] property to our projects that depend on the setup project and pass into the array the name of of our dependency project, which we defined in the previous step:

```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';
Expand All @@ -25,26 +44,182 @@ export default defineConfig({
use: { ...devices['Desktop Chrome'] },
dependencies: ['setup'],
},
]
});
```
### Setup Example

This example will show you how to use project dependencies to create a global setup that logins into an application and saves the state in storage state. This is useful if you want to run multiple tests that require a sign sign-in state and you want to avoid login for each test.

The setup project will write the storage state into an 'playwright/.auth/user.json' file next to your playwright.config. By exporting a const of `STORAGE_STATE` we can then easily share the location of the storage file between projects with the [`StorageState`](./test-use-options#basic-options) method. This applies the storage state on the browser context with its cookies and a local storage snapshot.

In this example the 'logged in chromium' project depends on the setup project whereas the 'logged out chromium' project does not depend on the setup project, and does not use the `storageState` option.

```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';

export const STORAGE_STATE = path.join(__dirname, 'playwright/.auth/user.json');

export default defineConfig({
use: {
baseURL: 'http://localhost:3000/',
},
projects: [
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
dependencies: ['setup'],
name: 'setup',
testMatch: /global.setup\.ts/,
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
name: 'logged in chromium',
use: { ...devices['Desktop Chrome'] },
testMatch: '**/*.loggedin.spec.ts',
dependencies: ['setup'],
use: {
storageState: STORAGE_STATE,
},
},
{
name: 'logged out chromium',
use: { ...devices['Desktop Chrome'] },
testIgnore: ['**/*loggedin.spec.ts']
},
],
});
```

We then create a setup test, stored at root level of your project, that logs in to an application and populates the context with the storage state after the login actions have been performed. By doing this you only have to log in once and the credentials will be stored in the `STORAGE_STATE` file, meaning you don't need to log in again for every test. Start by importing the `STORAGE_STATE` from the Playwright config file and then use this as the path to save your storage state to the page's context.

```js title="global.setup.ts"
import { test as setup, expect } from '@playwright/test';
import { STORAGE_STATE } from '../playwright.config';

setup('do login', async ({ page }) => {
await page.goto('/');
await page.getByLabel('User Name').fill('user');
await page.getByLabel('Password').fill('password');
await page.getByText('Sign in').click();

// Wait until the page actually signs in.
await expect(page.getByText('Hello, user!')).toBeVisible();

await page.context().storageState({ path: STORAGE_STATE });
});
```

```js title="tests/menu.loggedin.spec.ts"
import { test, expect } from '@playwright/test';

test.beforeEach(async ({ page }) => {
await page.goto('/');
});

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.

### Teardown

You can teardown your setup by adding a [`property: TestProject.teardown`] property to your setup project. This will run after all dependent projects have run.

First we add a new project into the projects array and give it a name such as 'cleanup db'. We then give it a [`property: TestProject.testMatch`] property in order to match the file called `global.teardown.ts`:

```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
// {
// setup project
// },
{
name: 'cleanup db',
testMatch: /global.teardown\.ts/,
},
// {
// other project
// }
]
});
```
Then we add the [`property: TestProject.teardown`] property to our setup project with the name 'cleanup db' which is the name we gave to our teardown project in the previous step:

```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'setup db',
testMatch: /global\.setup\.ts/,
teardown: 'cleanup db',
},
{
name: 'cleanup db',
testMatch: /global\.teardown\.ts/,
},
// {
// other project
// }
]
});
```

### Teardown Example

Start by creating a `global.setup.ts` file at the root level of your project. This will be used to seed the database with some data before all tests have run.

```js title="global.setup.ts"
// seed the database with some data
```
Then create a `global.teardown.ts` file at the root level of your project. This will be used to delete the data from the database after all tests have run.

```js title="global.teardown.ts"
// delete the data from the database
```
In the Playwright config file:
- Add a project into the projects array and give it a name such as 'setup db'. Give it a [`property: TestProject.testMatch`] property in order to match the file called `global.setup.ts`.

- Create another project and give it a name such as 'cleanup db'. Give it a [`property: TestProject.testMatch`] property in order to match the file called `global.teardown.ts`.

- Add the [`property: TestProject.teardown`] property to our setup project with the name 'cleanup db' which is the name given to our teardown project in the previous step. Finally add the 'chromium' project with the [`property: TestProject.dependencies`] on the 'setup db' project.


```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'setup db',
testMatch: /global\.setup\.ts/,
teardown: 'cleanup db',
},
{
name: 'cleanup db',
testMatch: /global\.teardown\.ts/,
},
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
dependencies: ['setup db'],
},
]
});
```

## Configure globalSetup and globalTeardown

You can use the `globalSetup` option in the [configuration file](#configuration-object) to set something up once before running all tests. The global setup file must export a single function that takes a config object. This function will be run once before all the tests.

Similarly, use `globalTeardown` to run something once after all the tests. Alternatively, let `globalSetup` return a function that will be used as a global teardown. You can pass data such as port number, authentication tokens, etc. from your global setup to your tests using environment variables.

:::note
Using `globalSetup` and `globalTeardown` will not produce traces or artifacts. If you want to produce traces and artifacts, use [project dependencies](#project-dependencies).
:::

```js title="playwright.config.ts"
import { defineConfig } from '@playwright/test';

Expand Down
9 changes: 8 additions & 1 deletion docs/src/test-projects-js.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@ export default defineConfig({
],
});
```

### Running Sequence

When working with tests that have a dependency, the dependency will always run first and once all tests from this project have passed, then the other projects will run in parallel.
Expand All @@ -206,6 +205,14 @@ Running order:

<img width="70%" style={{display: 'flex', margin: 'auto'}} alt="Browser login project is blue, database is red and e2e tests relies on both" loading="lazy" src="https://user-images.githubusercontent.com/13063165/225938262-33c1b78f-f092-4762-a478-7f8cbc1e3b21.jpg" />

### Teardown

You can also [`property: TestProject.teardown`] your setup by adding a teardown property to your setup project. This will run after all dependent projects have run. See the [teardown guide](./test-global-setup-teardown.md#teardown) for more information.


<img style={{display: 'flex', margin: 'auto'}} alt="global setup and teardown" loading="lazy" src="https://github.com/microsoft/playwright/assets/13063165/dfcf10a9-f601-4d0c-bd8d-9490e6efbf7a" />


## Custom project parameters

Projects can be also used to parametrize tests with your custom configuration - take a look at [this separate guide](./test-parameterize.md#parameterized-projects).

0 comments on commit 615e2e8

Please sign in to comment.