Back to All Questions
Question 28 of 100
Framework
Advanced
What are the key differences between fixtures and beforeEach hook?
The Answer
Both set up test state, but fixtures are composable, type-safe, reusable across files, and support lazy initialization. `beforeEach` is simpler but file-scoped and not reusable.
Deep Dive Explanation
Key differences: 1) Fixtures are lazy (only created if requested). 2) Fixtures are composable (one fixture can use another). 3) Fixtures can be shared across test files by exporting them. 4) Fixtures have automatic teardown via the `use()` callback pattern.
example.spec.ts
// beforeEach approach (file-scoped, not reusable)
test.beforeEach(async ({ page }) => {
await page.goto('/login');
await page.fill('#user', 'admin');
await page.fill('#pass', 'secret');
await page.click('#submit');
});
// Fixture approach (reusable across files, type-safe)
const test = base.extend<{ loggedInPage: Page }>({
loggedInPage: async ({ page }, use) => {
await page.goto('/login');
await page.fill('#user', 'admin');
await page.fill('#pass', 'secret');
await page.click('#submit');
await use(page); // hand off to test
// teardown runs here automatically
}
});