feat: add Playwright E2E testing setup with POM and testids

- Install @playwright/test and Chromium browser
- Create playwright.config.ts with dev server integration
- Add data-testid attributes to LoginPage, DashboardPage, ServerCard, Sidebar
- Exclude tests-e2e from vitest config
- Create Page Object Models: LoginPage, DashboardPage
- Add 18 E2E tests: 6 login flow, 12 dashboard (happy, empty, error states)
- Add test:e2e and test:e2e:ui scripts to package.json
This commit is contained in:
Tran G. (Revernomad) Khoa
2026-04-17 00:01:11 +07:00
parent 88424675b5
commit 620429c9b8
12 changed files with 471 additions and 11 deletions

View File

@@ -23,6 +23,7 @@
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@playwright/test": "^1.59.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
@@ -919,6 +920,22 @@
"url": "https://github.com/sponsors/Boshen"
}
},
"node_modules/@playwright/test": {
"version": "1.59.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz",
"integrity": "sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.59.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.0.0-rc.15",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.15.tgz",
@@ -4284,6 +4301,53 @@
"node": ">= 6"
}
},
"node_modules/playwright": {
"version": "1.59.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",
"integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.59.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.59.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz",
"integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/postcss": {
"version": "8.5.10",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.10.tgz",

View File

@@ -9,7 +9,9 @@
"lint": "eslint .",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
"test:watch": "vitest",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui"
},
"dependencies": {
"@hookform/resolvers": "^5.2.2",
@@ -27,6 +29,7 @@
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@playwright/test": "^1.59.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",

View File

@@ -0,0 +1,33 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests-e2e",
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
["html", { outputFolder: "playwright-report" }],
["list"],
],
use: {
baseURL: process.env.BASE_URL || "http://localhost:5173",
trace: "on-first-retry",
screenshot: "only-on-failure",
video: "retain-on-failure",
actionTimeout: 10_000,
navigationTimeout: 30_000,
},
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
],
webServer: {
command: "npm run dev",
url: "http://localhost:5173",
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
});

View File

@@ -11,7 +11,7 @@ export function Sidebar() {
const activeId = serverId ? parseInt(serverId) : null;
return (
<nav className="w-64 h-screen bg-surface-base border-r border-surface-raised flex flex-col">
<nav className="w-64 h-screen bg-surface-base border-r border-surface-raised flex flex-col" data-testid="sidebar">
<div className="px-6 py-5 border-b border-surface-raised">
<h1 className="text-text-primary font-bold text-lg tracking-tight">
<span className="text-accent">Languard</span>

View File

@@ -46,7 +46,7 @@ export function ServerCard({ server }: ServerCardProps) {
};
return (
<div className="neu-card p-5 flex flex-col gap-4">
<div className="neu-card p-5 flex flex-col gap-4" data-testid={`server-card-${server.id}`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2.5">
<StatusLed status={server.status} />

View File

@@ -12,7 +12,7 @@ export function DashboardPage() {
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<div className="flex items-center justify-center h-64" data-testid="dashboard-loading">
<div className="text-text-secondary">Loading servers...</div>
</div>
);
@@ -20,14 +20,14 @@ export function DashboardPage() {
if (isError) {
return (
<div className="flex items-center justify-center h-64">
<div className="flex items-center justify-center h-64" data-testid="dashboard-error">
<div className="text-status-crashed">Failed to load servers</div>
</div>
);
}
return (
<div className="p-6">
<div className="p-6" data-testid="dashboard-content">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-text-primary font-bold text-xl">Dashboard</h1>
@@ -35,14 +35,14 @@ export function DashboardPage() {
{servers?.length ?? 0} server{servers?.length !== 1 ? "s" : ""} configured
</p>
</div>
<Link to="/servers/new" className="btn-primary flex items-center gap-1.5 text-sm">
<Link to="/servers/new" className="btn-primary flex items-center gap-1.5 text-sm" data-testid="add-server-btn">
<Plus size={14} />
Add Server
</Link>
</div>
{servers?.length === 0 ? (
<div className="neu-card p-12 text-center">
<div className="neu-card p-12 text-center" data-testid="dashboard-empty">
<p className="text-text-secondary">No servers configured yet.</p>
<Link to="/servers/new" className="btn-primary mt-4 inline-flex items-center gap-2">
<Plus size={14} />

View File

@@ -45,7 +45,7 @@ export function LoginPage() {
return (
<div className="min-h-screen bg-surface-base flex items-center justify-center p-4">
<div className="neu-card p-8 w-full max-w-sm">
<div className="neu-card p-8 w-full max-w-sm" data-testid="login-card">
<div className="text-center mb-8">
<h1 className="text-2xl font-bold text-text-primary">
<span className="text-accent">Languard</span>
@@ -53,7 +53,7 @@ export function LoginPage() {
<p className="text-text-secondary text-sm mt-1">Server Manager</p>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" data-testid="login-form">
<div>
<label className="block text-text-secondary text-sm mb-1.5" htmlFor="username">
Username
@@ -63,6 +63,7 @@ export function LoginPage() {
type="text"
autoComplete="username"
className="neu-input w-full"
data-testid="login-username"
{...register("username")}
/>
{errors.username && (
@@ -79,6 +80,7 @@ export function LoginPage() {
type="password"
autoComplete="current-password"
className="neu-input w-full"
data-testid="login-password"
{...register("password")}
/>
{errors.password && (
@@ -87,7 +89,7 @@ export function LoginPage() {
</div>
{error && (
<div className="bg-surface-recessed border border-status-crashed rounded-lg px-3 py-2">
<div className="bg-surface-recessed border border-status-crashed rounded-lg px-3 py-2" data-testid="login-error">
<p className="text-status-crashed text-sm">{error}</p>
</div>
)}
@@ -96,6 +98,7 @@ export function LoginPage() {
type="submit"
disabled={isSubmitting}
className="btn-primary w-full mt-2"
data-testid="login-submit"
>
{isSubmitting ? "Signing in..." : "Sign In"}
</button>

View File

@@ -0,0 +1,95 @@
import { test, expect } from "@playwright/test";
import { LoginPage } from "../pages/LoginPage";
test.describe("Login Flow", () => {
let loginPage: LoginPage;
test.beforeEach(async ({ page }) => {
loginPage = new LoginPage(page);
await loginPage.goto();
});
test("should display login form", async () => {
await expect(loginPage.card).toBeVisible();
await expect(loginPage.usernameInput).toBeVisible();
await expect(loginPage.passwordInput).toBeVisible();
await expect(loginPage.submitButton).toBeVisible();
await expect(loginPage.submitButton).toContainText("Sign In");
});
test("should show Languard branding", async () => {
await expect(loginPage.card.locator("h1")).toContainText("Languard");
await expect(loginPage.card.locator("p")).toContainText("Server Manager");
});
test("should show validation errors on empty submit", async ({ page }) => {
await loginPage.submitButton.click();
await expect(page.locator("text=Username is required")).toBeVisible();
await expect(page.locator("text=Password is required")).toBeVisible();
});
test("should show error on invalid credentials", async ({ page }) => {
await loginPage.login("invalid", "credentials");
await page.waitForResponse(
(resp) => resp.url().includes("/api/auth/login"),
{ timeout: 10_000 },
).catch(() => {});
await expect(loginPage.errorMessage).toBeVisible({ timeout: 10_000 });
});
test("should navigate to dashboard on successful login", async ({ page }) => {
await page.route("**/api/auth/login", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
success: true,
data: {
access_token: "mock-jwt-token",
user: { id: 1, username: "admin", role: "admin" },
},
}),
}),
);
await page.route("**/api/servers*", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ success: true, data: [] }),
}),
);
await loginPage.login("admin", "password");
await page.waitForURL("/", { timeout: 10_000 });
await expect(page.locator("text=Dashboard")).toBeVisible();
});
test("should show loading state while submitting", async ({ page }) => {
await page.route("**/api/auth/login", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
success: true,
data: {
access_token: "mock-jwt-token",
user: { id: 1, username: "admin", role: "admin" },
},
}),
delay: 500,
}),
);
await page.route("**/api/servers*", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ success: true, data: [] }),
}),
);
await loginPage.login("admin", "password");
await expect(loginPage.submitButton).toContainText("Signing in...");
});
});

View File

@@ -0,0 +1,148 @@
import { test, expect } from "@playwright/test";
import { DashboardPage } from "../pages/DashboardPage";
test.describe("Dashboard", () => {
let dashboardPage: DashboardPage;
test.beforeEach(async ({ page }) => {
// Set up auth token so we're logged in
await page.addInitScript(() => {
localStorage.setItem("languard_token", "mock-jwt-token");
});
// Mock the servers API
await page.route("**/api/servers*", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
success: true,
data: [
{
id: 1,
name: "Arma3 Main Server",
game_type: "arma3",
status: "running",
port: 2302,
max_players: 64,
current_players: 32,
restart_count: 2,
auto_restart: true,
created_at: "2026-01-01T00:00:00Z",
},
{
id: 2,
name: "Arma3 Test Server",
game_type: "arma3",
status: "stopped",
port: 2303,
max_players: 32,
current_players: 0,
restart_count: 0,
auto_restart: false,
created_at: "2026-01-02T00:00:00Z",
},
],
}),
}),
);
dashboardPage = new DashboardPage(page);
await dashboardPage.goto();
});
test("should display dashboard header", async () => {
await expect(dashboardPage.content).toBeVisible();
await expect(dashboardPage.content.locator("h1")).toContainText("Dashboard");
});
test("should show server count", async () => {
await expect(dashboardPage.content.locator("text=2 servers configured")).toBeVisible();
});
test("should render server cards", async () => {
const count = await dashboardPage.getServerCount();
expect(count).toBe(2);
});
test("should display server names in cards", async () => {
const name = await dashboardPage.getServerCardName(0);
expect(name).toContain("Arma3 Main Server");
});
test("should show Add Server button", async () => {
await expect(dashboardPage.addServerButton).toBeVisible();
await expect(dashboardPage.addServerButton).toContainText("Add Server");
});
test("should show sidebar with server list", async () => {
await expect(dashboardPage.sidebar).toBeVisible();
await expect(dashboardPage.sidebar.locator("text=Servers")).toBeVisible();
await expect(dashboardPage.sidebar.locator("text=Arma3 Main Server")).toBeVisible();
});
test("should show Stop button for running server", async () => {
const firstCard = dashboardPage.serverCards.nth(0);
await expect(firstCard.locator('button[aria-label^="Stop"]')).toBeVisible();
});
test("should show Start button for stopped server", async () => {
const secondCard = dashboardPage.serverCards.nth(1);
await expect(secondCard.locator('button[aria-label^="Start"]')).toBeVisible();
});
test("should display player count in server card", async () => {
const firstCard = dashboardPage.serverCards.nth(0);
await expect(firstCard.locator("text=32/64")).toBeVisible();
});
test("should navigate to server detail on card click", async ({ page }) => {
const firstCard = dashboardPage.serverCards.nth(0);
const link = firstCard.locator("xpath=ancestor::a");
await link.click();
await expect(page).toHaveURL(/\/servers\/1/);
});
});
test.describe("Dashboard - Empty State", () => {
test("should show empty state when no servers", async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem("languard_token", "mock-jwt-token");
});
await page.route("**/api/servers*", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ success: true, data: [] }),
}),
);
const dashboardPage = new DashboardPage(page);
await dashboardPage.goto();
await expect(dashboardPage.emptyState).toBeVisible();
await expect(dashboardPage.emptyState.locator("text=No servers configured yet")).toBeVisible();
});
});
test.describe("Dashboard - Error State", () => {
test("should show error state when API fails", async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem("languard_token", "mock-jwt-token");
});
await page.route("**/api/servers*", (route) =>
route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ success: false, error: "Internal Server Error" }),
}),
);
const dashboardPage = new DashboardPage(page);
await dashboardPage.goto();
await expect(dashboardPage.errorMessage).toBeVisible({ timeout: 15_000 });
});
});

View File

@@ -0,0 +1,73 @@
import { Page, Locator } from "@playwright/test";
export class DashboardPage {
readonly page: Page;
readonly content: Locator;
readonly loading: Locator;
readonly errorMessage: Locator;
readonly emptyState: Locator;
readonly addServerButton: Locator;
readonly serverCards: Locator;
readonly sidebar: Locator;
constructor(page: Page) {
this.page = page;
this.content = page.locator('[data-testid="dashboard-content"]');
this.loading = page.locator('[data-testid="dashboard-loading"]');
this.errorMessage = page.locator('[data-testid="dashboard-error"]');
this.emptyState = page.locator('[data-testid="dashboard-empty"]');
this.addServerButton = page.locator('[data-testid="add-server-btn"]');
this.serverCards = page.locator("[data-testid^='server-card-']");
this.sidebar = page.locator('[data-testid="sidebar"]');
}
async goto() {
await this.page.goto("/");
await this.page.waitForLoadState("networkidle");
}
async waitForLoad() {
await this.loading.waitFor({ state: "hidden", timeout: 15_000 });
}
async getServerCount() {
return this.serverCards.count();
}
async getServerCardName(index: number) {
const card = this.serverCards.nth(index);
return card.locator("h2").textContent();
}
async getServerCardStatus(index: number) {
const card = this.serverCards.nth(index);
return card.locator("[data-testid^='server-card-']").getAttribute("data-testid");
}
async clickStartServer(index: number) {
const card = this.serverCards.nth(index);
const startBtn = card.locator('button[aria-label^="Start"]');
await startBtn.click();
}
async clickStopServer(index: number) {
const card = this.serverCards.nth(index);
const stopBtn = card.locator('button[aria-label^="Stop"]');
await stopBtn.click();
}
async clickRestartServer(index: number) {
const card = this.serverCards.nth(index);
const restartBtn = card.locator('button[aria-label^="Restart"]');
await restartBtn.click();
}
async clickAddServer() {
await this.addServerButton.click();
}
async clickSidebarServer(name: string) {
const link = this.sidebar.locator(`a:has-text("${name}")`);
await link.click();
}
}

View File

@@ -0,0 +1,40 @@
import { Page, Locator } from "@playwright/test";
export class LoginPage {
readonly page: Page;
readonly card: Locator;
readonly form: Locator;
readonly usernameInput: Locator;
readonly passwordInput: Locator;
readonly submitButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.card = page.locator('[data-testid="login-card"]');
this.form = page.locator('[data-testid="login-form"]');
this.usernameInput = page.locator('[data-testid="login-username"]');
this.passwordInput = page.locator('[data-testid="login-password"]');
this.submitButton = page.locator('[data-testid="login-submit"]');
this.errorMessage = page.locator('[data-testid="login-error"]');
}
async goto() {
await this.page.goto("/login");
await this.card.waitFor({ state: "visible" });
}
async login(username: string, password: string) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
await this.submitButton.click();
}
async getErrorMessage() {
return this.errorMessage.textContent();
}
async hasErrorMessage() {
return this.errorMessage.isVisible();
}
}

View File

@@ -14,5 +14,6 @@ export default defineConfig({
environment: "jsdom",
setupFiles: ["./src/__tests__/setup.ts"],
css: true,
exclude: ["node_modules", "tests-e2e", "**/tests-e2e/**"],
},
});