From 4532deb75349a37ab1a48d3cd6372cc90646d610 Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 3 Aug 2026 15:24:21 +0800 Subject: [PATCH] test(e2e): add domain-based auth and project web app e2e tests --- apps/web/e2e/fixtures.ts | 63 ++++++++++++++- apps/web/e2e/helpers/auth.ts | 76 +++++++++++++++++++ apps/web/e2e/helpers/project.ts | 29 +++++++ apps/web/e2e/helpers/ui.ts | 47 ++++++++++++ apps/web/e2e/tests/auth/invite-member.spec.ts | 58 ++++++++++++++ apps/web/e2e/tests/auth/login.spec.ts | 18 +++++ apps/web/e2e/tests/auth/signup.spec.ts | 24 ++++++ .../project/create-project.spec.ts} | 51 ++++--------- .../webui/routes/teams/$teamId/index.lazy.tsx | 1 + playwright.config.ts | 3 + 10 files changed, 332 insertions(+), 38 deletions(-) create mode 100644 apps/web/e2e/helpers/auth.ts create mode 100644 apps/web/e2e/helpers/project.ts create mode 100644 apps/web/e2e/helpers/ui.ts create mode 100644 apps/web/e2e/tests/auth/invite-member.spec.ts create mode 100644 apps/web/e2e/tests/auth/login.spec.ts create mode 100644 apps/web/e2e/tests/auth/signup.spec.ts rename apps/web/e2e/{signup-project.spec.ts => tests/project/create-project.spec.ts} (54%) diff --git a/apps/web/e2e/fixtures.ts b/apps/web/e2e/fixtures.ts index 87ea3738..6ef1600b 100644 --- a/apps/web/e2e/fixtures.ts +++ b/apps/web/e2e/fixtures.ts @@ -1,10 +1,20 @@ import { test as base } from '@playwright/test' +import type { BrowserContext, Page } from '@playwright/test' import { PrismaClient } from '../../../packages/db/src/generated/prisma/client' import { PrismaPg } from '@prisma/adapter-pg' import { Pool } from 'pg' import * as fs from 'fs' import * as path from 'path' import { fileURLToPath } from 'url' +import { + E2E_APP_URL, + E2E_PASSWORD, + apiSignup, + injectAuthState, + resolveTeamId, + uniqueEmail, +} from './helpers/auth' +import { apiCreateProject, uniqueProjectName } from './helpers/project' const currentDir = path.dirname(fileURLToPath(import.meta.url)) const envPath = path.resolve(currentDir, '.env.e2e') @@ -22,7 +32,25 @@ if (fs.existsSync(envPath)) { }) } -export const test = base.extend<{ prisma: PrismaClient }>({ +export interface OwnerFixture { + /** Page opened in a browser context logged in as the team owner. */ + page: Page + context: BrowserContext + teamId: string + email: string + password: string +} + +export interface ProjectFixture extends OwnerFixture { + projectId: string + projectName: string +} + +export const test = base.extend<{ + prisma: PrismaClient + owner: OwnerFixture + project: ProjectFixture +}>({ prisma: [ // eslint-disable-next-line no-empty-pattern async ({}, use) => { @@ -51,6 +79,39 @@ export const test = base.extend<{ prisma: PrismaClient }>({ }, { auto: true }, ], + /** + * Sets up an authenticated team owner through the API (fast, no UI): creates + * the user, stores the session cookie in the browser context, injects the + * persisted auth state, and opens the team page. + */ + owner: async ({ browser }, use) => { + const context = await browser.newContext({ + // eslint-disable-next-line @typescript-eslint/naming-convention + baseURL: E2E_APP_URL, + }) + const email = uniqueEmail('owner') + const password = E2E_PASSWORD + try { + // Create the owner via the API so the session cookie lands in the context + const user = await apiSignup(context.request, email, password) + await injectAuthState(context, user) + const teamId = await resolveTeamId(context.request) + + // Open the app already logged in on the team page + const page = await context.newPage() + await page.goto(`/teams/${teamId}`) + + await use({ page, context, teamId, email, password }) + } finally { + await context.close() + } + }, + /** Sets up an authenticated team owner plus a project created via the API. */ + project: async ({ owner }, use) => { + const name = uniqueProjectName() + const project = await apiCreateProject(owner.context.request, owner.teamId, name) + await use({ ...owner, projectId: project.id, projectName: name }) + }, }) export { expect } from '@playwright/test' diff --git a/apps/web/e2e/helpers/auth.ts b/apps/web/e2e/helpers/auth.ts new file mode 100644 index 00000000..6efd955e --- /dev/null +++ b/apps/web/e2e/helpers/auth.ts @@ -0,0 +1,76 @@ +import type { APIRequestContext, BrowserContext } from '@playwright/test' + +/** Base URL of the fullstack app under test (must match playwright.config.ts). */ +export const E2E_APP_URL = process.env.E2E_APP_URL || 'http://localhost:5200' + +export const E2E_PASSWORD = 'Password123!' + +export function uniqueEmail(prefix = 'user'): string { + return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@shumai.local` +} + +export interface AuthUser { + id: string + email: string + name: string +} + +interface SignupResponse { + token?: string | null + user?: AuthUser + error?: { message?: string } | null +} + +/** + * Creates a user through the better-auth API. + * When passed a `context.request`, the session cookie is stored in the browser + * context and the user is logged in. + */ +export async function apiSignup( + request: APIRequestContext, + email: string, + password: string, + options: { inviteCode?: string } = {}, +): Promise { + const res = await request.post('/api/auth/sign-up/email', { + data: { + name: email, + email, + password, + ...(options.inviteCode ? { inviteCode: options.inviteCode } : {}), + }, + }) + if (!res.ok()) { + throw new Error(`Signup API failed (${res.status()}): ${await res.text()}`) + } + const body = (await res.json()) as SignupResponse + if (!body.user) { + throw new Error(`Signup API returned no user: ${JSON.stringify(body)}`) + } + return body.user +} + +/** + * Injects the persisted auth state (zustand `auth-storage`) so the app + * considers the session logged in. The session cookie must already be present + * in the context (created via `context.request`). + */ +export async function injectAuthState(context: BrowserContext, user: AuthUser): Promise { + await context.addInitScript((u) => { + localStorage.setItem('auth-storage', JSON.stringify({ state: { user: u }, version: 0 })) + }, user) +} + +/** Resolves the id of the first team for the authenticated request context. */ +export async function resolveTeamId(request: APIRequestContext): Promise { + const res = await request.get('/api/teams') + if (!res.ok()) { + throw new Error(`GET /api/teams failed (${res.status()}): ${await res.text()}`) + } + const body = (await res.json()) as { data: { id: string }[] } + const teamId = body.data?.[0]?.id + if (!teamId) { + throw new Error(`No team found in /api/teams response: ${JSON.stringify(body)}`) + } + return teamId +} diff --git a/apps/web/e2e/helpers/project.ts b/apps/web/e2e/helpers/project.ts new file mode 100644 index 00000000..ab12a7e5 --- /dev/null +++ b/apps/web/e2e/helpers/project.ts @@ -0,0 +1,29 @@ +import type { APIRequestContext } from '@playwright/test' + +export function uniqueProjectName(): string { + return `Project ${Date.now()}-${Math.random().toString(36).slice(2, 6)}` +} + +interface CreateProjectResponse { + id?: string + name?: string +} + +/** Creates a project through the API for the authenticated request context. */ +export async function apiCreateProject( + request: APIRequestContext, + teamId: string, + name: string, +): Promise<{ id: string; name: string }> { + const res = await request.post(`/api/teams/${teamId}/projects`, { + data: { name }, + }) + if (!res.ok()) { + throw new Error(`Create project API failed (${res.status()}): ${await res.text()}`) + } + const body = (await res.json()) as CreateProjectResponse + if (!body.id || !body.name) { + throw new Error(`Create project returned an unexpected response: ${JSON.stringify(body)}`) + } + return { id: body.id, name: body.name } +} diff --git a/apps/web/e2e/helpers/ui.ts b/apps/web/e2e/helpers/ui.ts new file mode 100644 index 00000000..5b0296b2 --- /dev/null +++ b/apps/web/e2e/helpers/ui.ts @@ -0,0 +1,47 @@ +import { expect, type Locator, type Page } from '@playwright/test' + +export function parseTeamIdFromUrl(url: string): string { + const match = url.match(/\/teams\/([^/]+)/) + if (!match) throw new Error(`Could not parse teamId from URL: ${url}`) + return match[1] +} + +/** Performs the signup UI flow and waits for the redirect to the team page. */ +export async function signupViaUi(page: Page, email: string, password: string): Promise { + await page.goto('/signup') + await page.fill('#email', email) + await page.fill('#password', password) + await page.click('button[type="submit"]') + await page.waitForURL(/\/teams\/[^/]+/) + return parseTeamIdFromUrl(page.url()) +} + +/** Performs the login UI flow and waits for the redirect to the team page. */ +export async function loginViaUi(page: Page, email: string, password: string): Promise { + await page.goto('/login') + await page.fill('#email', email) + await page.fill('#password', password) + await page.click('button[type="submit"]') + await page.waitForURL(/\/teams\/[^/]+/) + return parseTeamIdFromUrl(page.url()) +} + +/** Opens the team members dialog from the team page header. */ +export async function openMembersDialog(page: Page): Promise { + await page.getByTestId('team-members-trigger').click() + const dialog = page.locator('[role="dialog"]') + await expect(dialog).toBeVisible() + return dialog +} + +/** Clicks "Generate Link" in the members dialog and returns the invite link. */ +export async function generateInviteLink(dialog: Locator): Promise { + await dialog.getByRole('button', { name: 'Generate Link' }).click() + const inviteInput = dialog.locator('input[readonly]') + await expect(inviteInput).toBeVisible() + const inviteLink = await inviteInput.inputValue() + if (!inviteLink.includes('inviteCode=')) { + throw new Error(`Unexpected invite link: ${inviteLink}`) + } + return inviteLink +} diff --git a/apps/web/e2e/tests/auth/invite-member.spec.ts b/apps/web/e2e/tests/auth/invite-member.spec.ts new file mode 100644 index 00000000..f2e10a51 --- /dev/null +++ b/apps/web/e2e/tests/auth/invite-member.spec.ts @@ -0,0 +1,58 @@ +import { expect, test } from '../../fixtures' +import { E2E_PASSWORD, uniqueEmail } from '../../helpers/auth' +import { generateInviteLink, openMembersDialog } from '../../helpers/ui' + +test('owner invites a member via invite link and the invitee joins', async ({ + owner, + browser, + prisma, +}) => { + const { page, teamId } = owner + + // 1. Open the team members dialog and generate an invite link + const dialog = await openMembersDialog(page) + const inviteLink = await generateInviteLink(dialog) + + const inviteCode = new URL(inviteLink).searchParams.get('inviteCode') + if (!inviteCode) { + throw new Error(`Invite link is missing the inviteCode param: ${inviteLink}`) + } + const origin = new URL(page.url()).origin + expect(inviteLink.startsWith(`${origin}/signup?inviteCode=`)).toBe(true) + + // 2. The invitee opens the link in a brand-new session (no cookies) + const inviteeContext = await browser.newContext() + const inviteePage = await inviteeContext.newPage() + const inviteeEmail = uniqueEmail('invitee') + try { + await inviteePage.goto(inviteLink) + + // The invite context banner is shown on the signup page + await expect(inviteePage.getByText(/invited you to join/)).toBeVisible() + + // 3. The invitee signs up through the invite flow + await inviteePage.fill('#email', inviteeEmail) + await inviteePage.fill('#password', E2E_PASSWORD) + await inviteePage.click('button[type="submit"]') + + // The invitee is redirected to the shared team + await expect(inviteePage).toHaveURL(/\/teams\/[^/]+/) + } finally { + await inviteeContext.close() + } + + // 4. The owner reloads and sees the new member in the members dialog + await page.reload() + const membersDialog = await openMembersDialog(page) + await expect(membersDialog).toContainText(inviteeEmail) + + // 5. DB: the invitee is a team member and the invite was consumed + const membershipCount = await prisma.teamMember.count({ where: { teamId } }) + expect(membershipCount).toBe(2) + + const invite = await prisma.invite.findUnique({ where: { code: inviteCode } }) + expect(invite?.used).toBe(true) + + const inviteeUser = await prisma.user.findUnique({ where: { email: inviteeEmail } }) + expect(inviteeUser).not.toBeNull() +}) diff --git a/apps/web/e2e/tests/auth/login.spec.ts b/apps/web/e2e/tests/auth/login.spec.ts new file mode 100644 index 00000000..abe7faac --- /dev/null +++ b/apps/web/e2e/tests/auth/login.spec.ts @@ -0,0 +1,18 @@ +import { expect, test } from '../../fixtures' +import { apiSignup, E2E_PASSWORD, uniqueEmail } from '../../helpers/auth' +import { loginViaUi } from '../../helpers/ui' + +test('should log in with existing credentials', async ({ page, request }) => { + const email = uniqueEmail('login') + const password = E2E_PASSWORD + + // Seed an existing user through the API (setup, not the flow under test) + await apiSignup(request, email, password) + + // The default page context is a fresh, logged-out session + await loginViaUi(page, email, password) + + // The logged-in user lands on their team page + await expect(page).toHaveURL(/\/teams\/[^/]+/) + await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible() +}) diff --git a/apps/web/e2e/tests/auth/signup.spec.ts b/apps/web/e2e/tests/auth/signup.spec.ts new file mode 100644 index 00000000..e8b6fd52 --- /dev/null +++ b/apps/web/e2e/tests/auth/signup.spec.ts @@ -0,0 +1,24 @@ +import { expect, test } from '../../fixtures' +import { E2E_PASSWORD, uniqueEmail } from '../../helpers/auth' +import { signupViaUi } from '../../helpers/ui' + +test('should sign up as the first user and become the team owner', async ({ page, prisma }) => { + const email = uniqueEmail('signup') + const password = E2E_PASSWORD + + const teamId = await signupViaUi(page, email, password) + + // The first user is redirected to their single team + await expect(page).toHaveURL(/\/teams\/[^/]+/) + await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible() + + // The new user exists and is the owner of the team + const user = await prisma.user.findUnique({ where: { email } }) + expect(user).not.toBeNull() + + const membership = await prisma.teamMember.findUnique({ + where: { teamIdUserId: { teamId, userId: user!.id } }, + }) + expect(membership?.role).toBe('owner') + expect(membership?.scope).toBe('team') +}) diff --git a/apps/web/e2e/signup-project.spec.ts b/apps/web/e2e/tests/project/create-project.spec.ts similarity index 54% rename from apps/web/e2e/signup-project.spec.ts rename to apps/web/e2e/tests/project/create-project.spec.ts index adb663e1..599050ef 100644 --- a/apps/web/e2e/signup-project.spec.ts +++ b/apps/web/e2e/tests/project/create-project.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from './fixtures' +import { expect, test } from '../../fixtures' import * as fs from 'fs' import * as path from 'path' import { fileURLToPath } from 'url' @@ -19,57 +19,34 @@ test.afterAll(async () => { } }) -test('should sign up and create a project with a cover image', async ({ page }) => { - const email = `test-${Date.now()}@shumai.local` - const password = 'Password123!' - - // 1. Sign Up Flow - await page.goto('/signup') - await expect(page).toHaveURL(/\/signup/) - - // Fill credentials - await page.fill('#email', email) - await page.fill('#password', password) - - // Submit sign up - await page.click('button[type="submit"]') - - // Wait for the automatic redirect to the team page (since only one team exists) - await expect(page).toHaveURL(/\/teams\/[^/]+/) - - // 2. Create Project Flow - // Click the "Create Project" button on the dashboard - await page.click('button:has-text("Create Project")') +test('owner should create a project with a cover image', async ({ owner, prisma }) => { + const { page, teamId } = owner + const projectName = `My Project ${Date.now()}` + // Open the create project dialog + await page.getByRole('button', { name: 'Create Project' }).click() const dialog = page.locator('[role="dialog"]') await expect(dialog).toBeVisible() - // Fill project name - const projectName = `My Project ${Date.now()}` + // Fill in project details and upload a cover image await dialog.locator('#name').fill(projectName) - - // Set cover image await dialog.locator('input[type="file"]').setInputFiles(tempImgPath) // Wait for image upload completion and preview await expect(dialog.locator('img[alt="Cover Preview"]')).toBeVisible({ timeout: 15_000 }) - // Click submit in dialog + // Submit and land on the project page await dialog.locator('button[type="submit"]').click() - - // Wait for navigation to the project page await expect(page).toHaveURL(/\/projects\/[^/]+/) - - // Verify project name appears in the project view await expect(page.locator(`text=${projectName}`).first()).toBeVisible() - // 3. Verification on Dashboard - // Navigate back to the dashboard via sidebar + // Back on the dashboard the new project card is visible with its cover await page.click('button[aria-label="Dashboard"]') - - // Wait for dashboard URL await expect(page).toHaveURL(/\/teams\/[^/]+/) - - // Verify the project card is visible and displays the cover image with project name alt text await expect(page.locator(`img[alt="${projectName}"]`)).toBeVisible() + + // The project was persisted for the owner's team + const project = await prisma.project.findFirst({ where: { name: projectName } }) + expect(project).not.toBeNull() + expect(project?.teamId).toBe(teamId) }) diff --git a/packages/webui/routes/teams/$teamId/index.lazy.tsx b/packages/webui/routes/teams/$teamId/index.lazy.tsx index ec4b8ca6..3361d094 100644 --- a/packages/webui/routes/teams/$teamId/index.lazy.tsx +++ b/packages/webui/routes/teams/$teamId/index.lazy.tsx @@ -261,6 +261,7 @@ function TeamPage() {
setIsMembersDialogOpen(true)} + data-testid="team-members-trigger" > {safeMembers.slice(0, 3).map((member) => ( diff --git a/playwright.config.ts b/playwright.config.ts index ffaefaaf..0f7784da 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -58,6 +58,7 @@ export default defineConfig({ { name: 'app-chromium', testDir: './apps/web/e2e', + workers: 1, // single worker so tests sharing the e2e database run serially fullyParallel: false, // run sequentially to avoid DB and storage conflicts use: { ...devices['Desktop Chrome'], @@ -69,6 +70,7 @@ export default defineConfig({ name: 'app-firefox', testDir: './apps/web/e2e', dependencies: ['app-chromium'], + workers: 1, // single worker so tests sharing the e2e database run serially fullyParallel: false, use: { ...devices['Desktop Firefox'], @@ -80,6 +82,7 @@ export default defineConfig({ name: 'app-webkit', testDir: './apps/web/e2e', dependencies: ['app-firefox'], + workers: 1, // single worker so tests sharing the e2e database run serially fullyParallel: false, use: { ...devices['Desktop Safari'],