Skip to main content

Introduction

Test hooks allow you to set up and tear down test environments. Playwright provides four types of hooks that run at different stages of the test lifecycle.

Hook Types

From src/common/test.ts:50 and src/common/testType.ts:52-55:

beforeEach

Runs before each test in the describe block:

afterEach

Runs after each test in the describe block:

beforeAll

Runs once before all tests in the describe block:
beforeAll and afterAll hooks have limited fixture support. They cannot use test-scoped fixtures like page and context.

afterAll

Runs once after all tests in the describe block:

Hook Execution Order

From src/common/testType.ts:174-184:

Hook Titles

From src/common/testType.ts:174-184: You can provide descriptive titles for hooks:
Without a title, the default is "${hookType} hook":

Hooks with Fixtures

Hooks can use fixtures just like tests:

Fixture Limitations in beforeAll/afterAll

From src/index.ts:357-364: beforeAll and afterAll cannot use test-scoped fixtures:
Valid fixtures for beforeAll/afterAll:
  • Worker-scoped fixtures: browser, browserName, request
  • Custom worker-scoped fixtures

Hook Error Handling

If a hook fails, subsequent hooks and tests are affected:

beforeEach Failure

beforeAll Failure

Shared State Between Hooks

Use describe block scope to share state:

Hook Scope and Nesting

Hooks are scoped to their describe block and nested blocks:

Conditional Hooks

You can conditionally run hooks:

Hooks with TestInfo

Access test metadata in hooks:

Hooks vs Fixtures

Choose between hooks and fixtures based on your needs: Use Hooks When:
  • Setup affects multiple tests
  • Need to run code once per suite (beforeAll/afterAll)
  • Want explicit setup/teardown in test file
  • Sharing state between tests
Use Fixtures When:
  • Setup is reusable across files
  • Need automatic cleanup
  • Want dependency injection
  • Creating page objects or utilities

Hook Example

Fixture Example

Best Practices

  1. Keep hooks focused: Each hook should have a single responsibility
  2. Use beforeAll sparingly: Can lead to test interdependence
  3. Always clean up: Use afterEach/afterAll for cleanup
  4. Handle errors gracefully: Add try-catch for cleanup code
  5. Consider fixtures: For reusable setup across files
  6. Use descriptive titles: Make hooks easier to understand in reports
  7. Avoid shared mutable state: Can cause flaky tests

Common Patterns

Authentication Setup

Database Seeding

Browser Context Configuration

Test Isolation

Next Steps

Test Fixtures

Learn about the fixture system

Parallelization

Run tests in parallel