Testing a Page with test.describe() and beforeEach()
Grouping a page's tests with test.describe() and navigating in beforeEach().
Use test.describe() to group all tests related to a page and test.beforeEach() to navigate to that page before every test.
Example
import { test, expect } from '@playwright/test';
test.describe('Login Page', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/login');
});
test('should display the login form', async ({ page }) => {
await expect(page.getByLabel('Email')).toBeVisible();
await expect(page.getByLabel('Password')).toBeVisible();
});
test('should display the login button', async ({ page }) => {
await expect(
page.getByRole('button', { name: 'Login' })
).toBeVisible();
});
test('should show an error for invalid credentials', async ({ page }) => {
await page.getByLabel('Email').fill('[email protected]');
await page.getByLabel('Password').fill('wrongpassword');
await page.getByRole('button', { name: 'Login' }).click();
await expect(
page.getByText(/invalid credentials/i)
).toBeVisible();
});
});
How It Works
test.describe()— Groups related tests for a page.test.beforeEach()— Runs before every test in the group.page.goto('/login')— Navigates to the login page before each test.test()— Defines an individual test case.expect()— Verifies the expected result.
Each test gets a fresh page by default, so tests are isolated from one another.
Running Tests
# Run all tests
npx playwright test
# Run a specific test file
npx playwright test tests/login.spec.ts
# Run tests matching a title
npx playwright test -g "Login Page"
# Run with a visible browser
npx playwright test tests/login.spec.ts --headed
Configuration
Configure baseURL in playwright.config.ts to use relative URLs:
use: {
baseURL: 'http://localhost:3000',
}
Best practice: Organize tests by page, using a separate test.describe() block or test file for Login, Signup, Dashboard, Settings, and other pages.