To set up a global afterEach
hook in @playwright/test that runs after every test regardless of the test outcome, you can use project dependencies. First, create a configuration file playwright.config.ts
and define your projects with their respective names, matchers (testMatch
), devices (use
), and dependencies:
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /global.setup\.ts/,
},
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
},
dependencies: ['setup'],
},
// ... other projects with dependencies
],
});
Here, we defined a 'setup' project and other projects that depend on it. The testMatch
property specifies which files should be included in each project.
Next, create an afterEach
function inside a global.setup.ts
file:
import { Fixture } from '@playwright/test';
const afterEach = async ({ page }: Fixture) => {
// Perform any necessary cleanup actions here
await page.close();
};
export default afterEach;
This afterEach
function takes an object with fixtures, which includes access to the same fixtures as the test function. In this example, we close the browser window after every test.
Now, when you run your tests using the Playwright Test runner (npx playwright test
), the global afterEach
hook will execute after each test, regardless of the test outcome.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].