Skip to contentPlayForge

How do I run code before each test in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

Put it in test.beforeEach(async ({ page }) => { ... }), which runs before every test in the same file, or the same test.describe block. When the same setup is needed in many files, or needs its own clean-up, a fixture is the better home.

This answer is one piece of Chapter 16: The Test Runner.

  • Test Structure & Lifecycle
  • playwright.config.ts Complete Reference
  • Test Organization at Scale
  • Tags, Grep, and the Suite You Actually Run
  • What Runs Where, and What Serial Costs
  • Practice and interview questions: Assertions & Test Runner

test.beforeEach() is the simplest way to share a few setup steps. It receives the same fixtures a test does, so it can open a page with page.goto() before each test starts. Its partner test.afterEach() runs after each test. Both apply only to the file, or the describe block, they are declared in.

That scope is the limit. If ten files need the same signed-in page, ten files repeat the hook. A fixture, defined once with test.extend(), can be used by any test that names it, keeps its setup and teardown together in one function, and runs only for tests that ask for it. Playwright's own page is a fixture for exactly these reasons.

A reasonable rule: use beforeEach for a line or two of setup that belongs to one file, such as opening the page under test. Move it into a fixture once it is copied between files or needs clean-up afterwards. See qa-016 for fixtures.

In the example, the hook opens the catalog before each test, so both tests start on the page with an empty cart and go straight to their own steps.

before-each.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test.beforeEach(async ({ page }) => { await page.goto('/catalog.html?mock=static&seed=42&autologin=1'); }); test('the cart starts empty', async ({ page }) => { await expect(page.getByTestId('cart-total')).toHaveText('₹0'); }); test('adding the grinder updates the total', async ({ page }) => { const grinder = page.locator('article[data-sku="MRD-1003"]'); await grinder.getByRole('button', { name: 'Add to cart' }).click(); await expect(page.getByTestId('cart-total')).toHaveText('₹11,900'); });
Output
2 passed (2.8s)
Test yourself
You declare test.beforeEach() at the top of cart.spec.js. Which tests does it run before?

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.