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
Fromsrc/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:afterAll
Runs once after all tests in the describe block:Hook Execution Order
Fromsrc/common/testType.ts:174-184:
Hook Titles
Fromsrc/common/testType.ts:174-184:
You can provide descriptive titles for hooks:
"${hookType} hook":
Hooks with Fixtures
Hooks can use fixtures just like tests:Fixture Limitations in beforeAll/afterAll
Fromsrc/index.ts:357-364:
beforeAll and afterAll cannot use test-scoped fixtures:
- 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
- Setup is reusable across files
- Need automatic cleanup
- Want dependency injection
- Creating page objects or utilities
Hook Example
Fixture Example
Best Practices
- Keep hooks focused: Each hook should have a single responsibility
- Use beforeAll sparingly: Can lead to test interdependence
- Always clean up: Use afterEach/afterAll for cleanup
- Handle errors gracefully: Add try-catch for cleanup code
- Consider fixtures: For reusable setup across files
- Use descriptive titles: Make hooks easier to understand in reports
- 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
