Master end-to-end testing with Playwright for Next.js applications. Learn page objects, fixtures, authentication, visual testing, API mocking, and CI/CD integration.
# Playwright E2E Testing Complete Guide
Build comprehensive end-to-end tests with Playwright for Next.js applications including authentication flows, visual regression, and CI integration.
## Project Setup
### Configuration
```typescript
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
["html", { open: "never" }],
["junit", { outputFile: "test-results/junit.xml" }],
],
use: {
baseURL: process.env.PLAYWRIGHT_BASE_URL || "http://localhost:3000",
trace: "on-first-retry",
screenshot: "only-on-failure",
video: "retain-on-failure",
},
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
{
name: "firefox",
use: { ...devices["Desktop Firefox"] },
},
{
name: "webkit",
use: { ...devices["Desktop Safari"] },
},
{
name: "mobile-chrome",
use: { ...devices["Pixel 5"] },
},
{
name: "mobile-safari",
use: { ...devices["iPhone 12"] },
},
],
webServer: {
command: "npm run dev",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
});
```
## Authentication Fixtures
### Reusable Auth State
```typescript
// e2e/fixtures/auth.ts
import { test as base, Page } from "@playwright/test";
interface User {
email: string;
password: string;
name: string;
}
interface AuthFixtures {
authenticatedPage: Page;
adminPage: Page;
}
async function login(page: Page, user: User) {
await page.goto("/login");
await page.getByLabel("Email").fill(user.email);
await page.getByLabel("Password").fill(user.password);
await page.getByRole("button", { name: "Sign in" }).click();
await page.waitForURL("/dashboard");
}
export const test = base.extend<AuthFixtures>({
authenticatedPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: "e2e/.auth/user.json",
});
const page = await context.newPage();
await use(page);
await context.close();
},
adminPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: "e2e/.auth/admin.json",
});
const page = await context.newPage();
await use(page);
await context.close();
},
});
// Global setup for auth state
// e2e/global-setup.ts
import { chromium } from "@playwright/test";
async function globalSetup() {
const browser = await chromium.launch();
// Setup regular user
const userContext = await browser.newContext();
const userPage = await userContext.newPage();
await userPage.goto("http://localhost:3000/login");
await userPage.getByLabel("Email").fill("user@example.com");
await userPage.getByLabel("Password").fill("password123");
await userPage.getByRole("button", { name: "Sign in" }).click();
await userPage.waitForURL("/dashboard");
await userContext.storageState({ path: "e2e/.auth/user.json" });
await userContext.close();
// Setup admin user
const adminContext = await browser.newContext();
const adminPage = await adminContext.newPage();
await adminPage.goto("http://localhost:3000/login");
await adminPage.getByLabel("Email").fill("admin@example.com");
await adminPage.getByLabel("Password").fill("adminpass123");
await adminPage.getByRole("button", { name: "Sign in" }).click();
await adminPage.waitForURL("/dashboard");
await adminContext.storageState({ path: "e2e/.auth/admin.json" });
await adminContext.close();
await browser.close();
}
export default globalSetup;
```
## Page Object Model
### Page Objects
```typescript
// e2e/pages/DashboardPage.ts
import { Page, Locator, expect } from "@playwright/test";
export class DashboardPage {
readonly page: Page;
readonly heading: Locator;
readonly createButton: Locator;
readonly projectList: Locator;
readonly searchInput: Locator;
readonly userMenu: Locator;
constructor(page: Page) {
this.page = page;
this.heading = page.getByRole("heading", { name: "Dashboard" });
this.createButton = page.getByRole("button", { name: "Create Project" });
this.projectList = page.getByTestId("project-list");
this.searchInput = page.getByPlaceholder("Search projects...");
this.userMenu = page.getByTestId("user-menu");
}
async goto() {
await this.page.goto("/dashboard");
await expect(this.heading).toBeVisible();
}
async createProject(name: string, description: string) {
await this.createButton.click();
await this.page.getByLabel("Project Name").fill(name);
await this.page.getByLabel("Description").fill(description);
await this.page.getByRole("button", { name: "Create" }).click();
await expect(this.page.getByText(`Project "${name}" created`)).toBeVisible();
}
async searchProjects(query: string) {
await this.searchInput.fill(query);
await this.page.waitForResponse((res) =>
res.url().includes("/api/projects") && res.status() === 200
);
}
async getProjectCount(): Promise<number> {
return this.projectList.locator("[data-testid=project-card]").count();
}
async logout() {
await this.userMenu.click();
await this.page.getByRole("menuitem", { name: "Logout" }).click();
await expect(this.page).toHaveURL("/login");
}
}
```
## Test Examples
### Feature Tests
```typescript
// e2e/tests/dashboard.spec.ts
import { expect } from "@playwright/test";
import { test } from "../fixtures/auth";
import { DashboardPage } from "../pages/DashboardPage";
test.describe("Dashboard", () => {
test("displays user projects", async ({ authenticatedPage }) => {
const dashboard = new DashboardPage(authenticatedPage);
await dashboard.goto();
await expect(dashboard.heading).toBeVisible();
const count = await dashboard.getProjectCount();
expect(count).toBeGreaterThanOrEqual(0);
});
test("creates a new project", async ({ authenticatedPage }) => {
const dashboard = new DashboardPage(authenticatedPage);
await dashboard.goto();
await dashboard.createProject("Test Project", "A test project description");
await expect(
authenticatedPage.getByText("Test Project")
).toBeVisible();
});
test("searches projects", async ({ authenticatedPage }) => {
const dashboard = new DashboardPage(authenticatedPage);
await dashboard.goto();
await dashboard.searchProjects("react");
await expect(dashboard.projectList).toContainText("react");
});
});
```
### API Mocking
```typescript
// e2e/tests/with-mocks.spec.ts
import { test, expect } from "@playwright/test";
test("handles API errors gracefully", async ({ page }) => {
// Mock API to return error
await page.route("**/api/projects", (route) => {
route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ error: "Internal server error" }),
});
});
await page.goto("/dashboard");
await expect(page.getByText("Something went wrong")).toBeVisible();
await expect(page.getByRole("button", { name: "Retry" })).toBeVisible();
});
test("displays loading state", async ({ page }) => {
await page.route("**/api/projects", async (route) => {
await new Promise((r) => setTimeout(r, 2000));
route.continue();
});
await page.goto("/dashboard");
await expect(page.getByTestId("loading-skeleton")).toBeVisible();
});
```
### Visual Regression
```typescript
// e2e/tests/visual.spec.ts
import { test, expect } from "@playwright/test";
test("homepage visual regression", async ({ page }) => {
await page.goto("/");
await expect(page).toHaveScreenshot("homepage.png", {
fullPage: true,
animations: "disabled",
});
});
test("dashboard visual regression", async ({ page }) => {
await page.goto("/dashboard");
await page.waitForLoadState("networkidle");
await expect(page.getByTestId("dashboard-content")).toHaveScreenshot(
"dashboard-content.png"
);
});
```
## CI Integration
```yaml
# .github/workflows/e2e.yml
name: E2E Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npx playwright install --with-deps
- run: npm run test:e2e
env:
PLAYWRIGHT_BASE_URL: http://localhost:3000
- uses: actions/upload-artifact@v4
if: failure()
with:
name: playwright-report
path: playwright-report/
```
This Playwright guide covers page objects, fixtures, authentication, mocking, visual testing, and CI integration.This playwright prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their playwright implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For playwright projects, consider mentioning your framework version, coding style, and any specific libraries you're using.