Open source personal finance application
test(e2e): drop email-auth dependent e2e suite
Ilya Komichev6f6ee36e7e58
diff --git a/app/package.json b/app/package.jsonindex 49b46a59..5f1cba95 100644--- a/app/package.json+++ b/app/package.json@@ -24,13 +24,10 @@"test": "vitest","test:coverage": "vitest run --coverage","test:e2e": "playwright test --project=demo",- "test:e2e:db:seed": "node scripts/seed-e2e-user.mjs","test:e2e:headed": "playwright test --project=demo --headed","test:e2e:ui": "playwright test --ui","test:e2e:report": "playwright show-report",- "test:e2e:install": "playwright install chromium",- "test:e2e:auth": "playwright test --project=auth-setup --headed",- "test:e2e:real": "playwright test --project=real"+ "test:e2e:install": "playwright install chromium"},"dependencies": {"@formkit/drag-and-drop": "^0.5.3",diff --git a/app/playwright.config.ts b/app/playwright.config.tsindex 6c305509..18c8490b 100644--- a/app/playwright.config.ts+++ b/app/playwright.config.ts@@ -1,45 +1,12 @@import { defineConfig, devices } from '@playwright/test'-import { existsSync } from 'node:fs'-import path from 'node:path'import process from 'node:process'-import { fileURLToPath } from 'node:url'--const dirname = path.dirname(fileURLToPath(import.meta.url))-const authFile = path.join(dirname, 'tests', 'e2e', '.auth', 'user.json')-const hasAuth = existsSync(authFile)export default defineConfig({projects: [{name: 'demo',- testIgnore: [/auth\.setup\.ts$/, /-real\.spec\.ts$/],use: { ...devices['Desktop Chrome'] },},- {- name: 'auth-setup',- testMatch: /auth\.setup\.ts$/,- use: {- ...devices['Desktop Chrome'],- channel: 'chrome',- launchOptions: {- args: ['--disable-blink-features=AutomationControlled'],- ignoreDefaultArgs: ['--enable-automation'],- },- },- },- {- name: 'real',- testMatch: /-real\.spec\.ts$/,- use: {- ...devices['Desktop Chrome'],- channel: 'chrome',- launchOptions: {- args: ['--disable-blink-features=AutomationControlled'],- ignoreDefaultArgs: ['--enable-automation'],- },- ...(hasAuth ? { storageState: authFile } : {}),- },- },],reporter: [['html', { open: 'never' }], ['list']],retries: 0,diff --git a/app/scripts/seed-e2e-user.mjs b/app/scripts/seed-e2e-user.mjsdeleted file mode 100644index 47b8a84c..00000000--- a/app/scripts/seed-e2e-user.mjs+++ /dev/null@@ -1,158 +0,0 @@-#!/usr/bin/env node-// Seed a fixed, reproducible e2e test account into the local Supabase stack.-//-// Why: the `real` Playwright project (`*-real.spec.ts`) needs a real signed-in-// session in `tests/e2e/.auth/user.json` AND some baseline data to act on.-// Regenerating the session (via `pnpm test:e2e:auth`) requires an account to log-// into; the category-children specs additionally need existing categories to-// pick as children. This script provisions both deterministically so any machine-// gets the same e2e account.-//-// It reads the local `service_role` key + API URL from `supabase status -o json`-// at run time (never hardcoded). The user is created via the GoTrue admin API-// (raw-SQL seeding of `auth.users` is avoided - it depends on GoTrue's bcrypt-// internals). Categories are upserted via PostgREST with the service_role key-// (bypasses RLS), then sync down to the client through PowerSync.-//-// Idempotent: re-running treats an existing user as success and re-upserts the-// categories with fixed ids, resetting them to root (parentId null) so a prior-// test run that reparented them does not leave the account in a dirty state.-//-// Credentials are LOCAL-DEV ONLY (the stack runs on localhost). Override with-// E2E_USER_EMAIL / E2E_USER_PASSWORD if you prefer different ones.-//-// Usage: pnpm test:e2e:db:seed (alias for `node scripts/seed-e2e-user.mjs`)-// Note: if pnpm's install gate blocks, run directly: `node scripts/seed-e2e-user.mjs`--import { execFileSync } from 'node:child_process'-import process from 'node:process'--const EMAIL = process.env.E2E_USER_EMAIL ?? '[email protected]'-const PASSWORD = process.env.E2E_USER_PASSWORD ?? 'e2e-finapp-test-pw'--// Baseline root categories the `*-real.spec.ts` specs pick as child candidates.-// Fixed ids -> idempotent upsert; parentId null -> root (the client maps null<->0).-const CATEGORY_COUNT = 12--function readSupabaseStatus() {- let raw- try {- raw = execFileSync('supabase', ['status', '-o', 'json'], {- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'pipe'],- })- }- catch (err) {- throw new Error(- `Failed to run \`supabase status -o json\`. Is the local stack up `- + `(\`supabase start\`)?\n${err.stderr || err.message}`,- )- }-- let status- try {- status = JSON.parse(raw)- }- catch {- throw new Error(`Could not parse \`supabase status -o json\` output:\n${raw}`)- }-- const apiUrl = status.API_URL- const serviceRoleKey = status.SERVICE_ROLE_KEY- if (!apiUrl || !serviceRoleKey)- throw new Error('supabase status is missing API_URL or SERVICE_ROLE_KEY - is the stack fully started?')-- return { apiUrl, serviceRoleKey }-}--function adminHeaders(serviceRoleKey) {- return {- 'apikey': serviceRoleKey,- 'Authorization': `Bearer ${serviceRoleKey}`,- 'Content-Type': 'application/json',- }-}--// Create the user (or treat "already exists" as success) and return its uid.-async function ensureUser(apiUrl, serviceRoleKey) {- const res = await fetch(`${apiUrl}/auth/v1/admin/users`, {- body: JSON.stringify({ email: EMAIL, email_confirm: true, password: PASSWORD }),- headers: adminHeaders(serviceRoleKey),- method: 'POST',- })- const body = await res.json().catch(() => ({}))-- if (res.ok) {- console.log(`Seeded e2e user: ${EMAIL} (id ${body.id})`)- return body.id- }-- // Idempotency: GoTrue returns 422 when the user already exists.- const code = body.error_code || body.code || ''- const msg = body.msg || body.message || ''- if (res.status === 422 && /already.*registered|already.*exists|email_exists/i.test(`${code} ${msg}`)) {- console.log(`e2e user already exists: ${EMAIL} (ok)`)- return resolveUid(apiUrl, serviceRoleKey)- }-- throw new Error(`Admin create failed (${res.status}): ${JSON.stringify(body)}`)-}--// Look up the existing user's uid by email via the GoTrue admin list endpoint.-async function resolveUid(apiUrl, serviceRoleKey) {- const res = await fetch(`${apiUrl}/auth/v1/admin/users?per_page=200`, {- headers: adminHeaders(serviceRoleKey),- })- const body = await res.json().catch(() => ({}))- const users = body.users ?? []- const found = users.find(u => u.email === EMAIL)- if (!found)- throw new Error(`Could not resolve uid for ${EMAIL} from admin user list`)- return found.id-}--// Upsert baseline root categories for the user (PostgREST, service_role bypasses RLS).-async function seedCategories(apiUrl, serviceRoleKey, uid) {- const now = Date.now()- const rows = Array.from({ length: CATEGORY_COUNT }, (_, i) => {- const n = String(i + 1).padStart(2, '0')- return {- color: '#4caf50',- icon: 'mdi:tag',- id: `e2e-cat-${n}`,- name: `E2E Category ${n}`,- parentId: null,- showInLastUsed: false,- showInQuickSelector: false,- updatedAt: now,- userId: uid,- }- })-- const res = await fetch(`${apiUrl}/rest/v1/categories`, {- body: JSON.stringify(rows),- headers: {- ...adminHeaders(serviceRoleKey),- // Upsert on the primary key so re-runs reset state instead of erroring.- Prefer: 'resolution=merge-duplicates,return=minimal',- },- method: 'POST',- })-- if (!res.ok) {- const text = await res.text().catch(() => '')- throw new Error(`Category seed failed (${res.status}): ${text}`)- }- console.log(`Seeded ${CATEGORY_COUNT} baseline categories for ${EMAIL}`)-}--async function seed() {- const { apiUrl, serviceRoleKey } = readSupabaseStatus()- const uid = await ensureUser(apiUrl, serviceRoleKey)- await seedCategories(apiUrl, serviceRoleKey, uid)-}--seed().catch((err) => {- console.error(err.message || err)- process.exitCode = 1-})diff --git a/app/tests/e2e/auth.setup.ts b/app/tests/e2e/auth.setup.tsdeleted file mode 100644index d5caa7f1..00000000--- a/app/tests/e2e/auth.setup.ts+++ /dev/null@@ -1,47 +0,0 @@-import { expect, test as setup } from '@playwright/test'-import path from 'node:path'-import process from 'node:process'-import { fileURLToPath } from 'node:url'--const dirname = path.dirname(fileURLToPath(import.meta.url))-const authFile = path.join(dirname, '.auth', 'user.json')--// Defaults match the fixed user created by `pnpm test:e2e:db:seed`-// (scripts/seed-e2e-user.mjs). Local-dev only. Override via env if needed.-const email = process.env.E2E_USER_EMAIL ?? '[email protected]'-const password = process.env.E2E_USER_PASSWORD ?? 'e2e-finapp-test-pw'--setup('authenticate', async ({ page }) => {- setup.setTimeout(5 * 60_000)-- const appUrl = /\/(dashboard|categories|wallets|stat|settings)/-- if (email && password) {- // Automated. Retry the whole goto -> fill -> submit because a cold dev server- // can full-reload mid-flight (Vite re-optimizes deps like motion-v on first- // visit and pushes a reload), which interrupts navigation or wipes the form.- // Once the deps are bundled a retry lands cleanly. type-based selectors are- // i18n-agnostic.- await expect(async () => {- await page.goto('/login', { waitUntil: 'domcontentloaded' })- await page.locator('input[type="email"]').fill(email)- await page.locator('input[type="password"]').fill(password)- await page.locator('button[type="submit"]').click()- await page.waitForURL(appUrl, { timeout: 15_000 })- }).toPass({ timeout: 4 * 60_000 })- }- else {- // Manual fallback: no credentials provided - sign in by hand in the window.- console.log(- '\n=== Auth setup ===\n'- + 'A browser window will open. Sign in with your Supabase email and password.\n'- + `The session will be saved to ${path.relative(process.cwd(), authFile)} once you reach the app.\n`,- )- await page.goto('/login')- await page.waitForURL(appUrl, { timeout: 5 * 60_000 })- }-- await page.context().storageState({ path: authFile })-- console.log(`Saved auth state to ${authFile}`)-})diff --git a/app/tests/e2e/categories-children-real.spec.ts b/app/tests/e2e/categories-children-real.spec.tsdeleted file mode 100644index a3e5dd19..00000000--- a/app/tests/e2e/categories-children-real.spec.ts+++ /dev/null@@ -1,385 +0,0 @@-import type { Page } from '@playwright/test'--import { expect, test } from '@playwright/test'-import { existsSync } from 'node:fs'-import path from 'node:path'-import { fileURLToPath } from 'node:url'--const dirname = path.dirname(fileURLToPath(import.meta.url))--const T = {- apply: /^(Apply|Применить)$/,- cancel: /^(Cancel|Отмена|Отменить)$/,- childCategories: /^(Child categories|Дочерние категории)$/,- // LayoutConfirmModal uses base.delete for the destructive action- confirm: /^(Delete|Удалить)$/,- parentCategory: /^(Parent category|Родительская категория)$/,- save: /^(Save|Сохранить)$/,- search: /(Search|Поиск)/i,- selectedAny: /(\d+ selected|Выбрано:?\s*\d+)/i,-}--const authFile = path.join(dirname, '.auth', 'user.json')--function uniqueName(suffix: string) {- const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)- return `E2E_${suffix}_${stamp}_${Math.random().toString(36).slice(2, 5)}`-}--async function waitForCategoryFormReady(page: Page) {- // Form is ready when the Save button appears (always present once the form mounts)- await page.getByRole('button', { name: T.save }).first().waitFor({- state: 'visible',- timeout: 30_000,- })-}--async function openChildrenModal(page: Page) {- const row = page.getByText(T.childCategories).first()- await expect(row).toBeVisible({ timeout: 10_000 })- await row.click()- await expect(page.locator('button[aria-pressed]').first()).toBeVisible({ timeout: 10_000 })-}--function candidateRows(page: Page) {- return page.locator('button[aria-pressed]')-}--async function getCandidateName(row: ReturnType<Page['locator']>) {- // Row = [checkbox, icon, CategoriesName]. The name is a `span.truncate`; an- // optional `div.truncate` (parent name) only renders for non-root candidates,- // so match any `.truncate` and take the first (the name always comes first).- const nameEl = row.locator('.truncate').first()- const text = (await nameEl.textContent()) ?? ''- return text.trim()-}--async function selectFirstNCandidates(page: Page, n: number): Promise<string[]> {- const rows = candidateRows(page)- const total = await rows.count()- const picked: string[] = []- for (let i = 0; i < Math.min(n, total); i++) {- const row = rows.nth(i)- const name = await getCandidateName(row)- await row.click()- picked.push(name)- }- return picked-}--// Bottom-anchored buttons (in bottom sheets / confirm dialogs) get covered by the-// Nuxt devtools container, which spans the viewport bottom in the dev server.-// `force: true` still does a coordinate click and lands on the devtools overlay,-// so use `dispatchEvent('click')` - it fires the handler directly on the element,-// independent of what overlaps it.-async function clickButton(page: Page, name: RegExp) {- await page.getByRole('button', { name }).first().dispatchEvent('click')-}--async function applyModal(page: Page) {- await clickButton(page, T.apply)-}--async function saveCategory(page: Page) {- await clickButton(page, T.save)-}--/**- * Create a fresh parent on /categories/new with N existing categories chosen as children.- * Returns the parent name, child names, and the freshly assigned id (from URL).- */-async function createParentWithChildren(page: Page, suffix: string, childCount = 2) {- const name = uniqueName(suffix)- await page.goto('/categories/new')- await waitForCategoryFormReady(page)- await openChildrenModal(page)- const children = await selectFirstNCandidates(page, childCount)- await applyModal(page)-- await page.getByRole('textbox').first().fill(name)- await saveCategory(page)- // After save, New.vue redirects to /categories/{id}. Wait for the post-redirect URL.- await page.waitForURL((url) => {- const m = url.pathname.match(/\/categories\/([^/]+)$/)- return !!m && m[1] !== 'new'- }, { timeout: 15_000 })- const url = page.url()- const id = url.split('/').pop()!- expect(id).toBeTruthy()- expect(id).not.toBe('new')- // setChildren mutation runs asynchronously after create resolves.- await page.waitForTimeout(2500)- return { children, id, name }-}--async function gotoEdit(page: Page, parentId: string) {- await page.goto(`/categories/${parentId}/edit`, { waitUntil: 'domcontentloaded' })- await page.getByRole('button', { name: T.save }).first().waitFor({- state: 'visible',- timeout: 30_000,- })-}--async function selectedNamesInModal(page: Page): Promise<string[]> {- const rows = candidateRows(page)- const total = await rows.count()- const out: string[] = []- for (let i = 0; i < total; i++) {- const row = rows.nth(i)- if (await row.getAttribute('aria-pressed') === 'true')- out.push(await getCandidateName(row))- }- return out-}--test.describe.configure({ timeout: 120_000 })--test.describe('Categories children - real backend', () => {- test.use({ actionTimeout: 15_000, navigationTimeout: 30_000 })-- test.beforeEach(async ({ context, page }) => {- if (!existsSync(authFile))- test.skip(true, `Run 'pnpm test:e2e:auth' first to save real-user auth state.`)- // Hide Nuxt devtools toolbar/frame - it intercepts clicks on bottom-anchored- // buttons (Apply / Save) inside bottom sheets.- await context.addInitScript(() => {- const css = `- nuxt-devtools-frame,- nuxt-devtools-anchor,- nuxt-devtools-container,- #nuxt-devtools-container,- [data-v-inspector-ignore="true"] { display: none !important; pointer-events: none !important; }- `- const apply = () => {- if (!document.head)- return- const id = '__e2e_hide_devtools__'- if (document.getElementById(id))- return- const style = document.createElement('style')- style.id = id- style.textContent = css- document.head.appendChild(style)- }- apply()- new MutationObserver(apply).observe(document.documentElement, { childList: true, subtree: true })- })- await page.context()- })-- test('creates new parent with two children', async ({ page }) => {- const { children, id, name } = await createParentWithChildren(page, 'create', 2)- expect(children).toHaveLength(2)- expect(id).toBeTruthy()- // After save we land on /categories/{id} (detail page). The detail page- // lists the parent's children. Verify they appear there directly.- for (const child of children)- await expect(page.getByText(child).first()).toBeVisible({ timeout: 10_000 })- // Page title reflects the parent's name- expect(await page.title()).toContain(name)- })-- test('edit: adds another child to existing parent', async ({ page }) => {- const { children, id } = await createParentWithChildren(page, 'add', 2)-- await gotoEdit(page, id)- await openChildrenModal(page)-- // Pick first non-pressed candidate that's not already a child- const rows = candidateRows(page)- const total = await rows.count()- let added = ''- for (let i = 0; i < total; i++) {- const row = rows.nth(i)- if (await row.getAttribute('aria-pressed') === 'true')- continue- const candidateName = await getCandidateName(row)- if (children.includes(candidateName))- continue- await row.click()- added = candidateName- break- }- expect(added, 'No additional candidate available to add').not.toBe('')-- await applyModal(page)- await saveCategory(page)- await page.waitForURL((url) => {- const m = url.pathname.match(/\/categories\/([^/]+)$/)- return !!m && m[1] !== 'new'- }, { timeout: 15_000 })- await page.waitForTimeout(2500)-- // Reopen edit, verify the new child is now selected- await gotoEdit(page, id)- await openChildrenModal(page)- const selected = await selectedNamesInModal(page)- expect(selected).toContain(added)- for (const original of children)- expect(selected).toContain(original)- })-- test('edit: removes single child without confirm dialog', async ({ page }) => {- const { children, id } = await createParentWithChildren(page, 'remove1', 2)-- await gotoEdit(page, id)- await openChildrenModal(page)-- const rows = candidateRows(page)- const total = await rows.count()- let removed = ''- for (let i = 0; i < total; i++) {- const row = rows.nth(i)- if (await row.getAttribute('aria-pressed') !== 'true')- continue- removed = await getCandidateName(row)- await row.click()- break- }- expect(removed, 'No selected child to remove').not.toBe('')-- // Single removal should NOT trigger the confirm dialog- await applyModal(page)- await expect(page.getByRole('button', { name: T.confirm })).toHaveCount(0)-- await saveCategory(page)- await page.waitForURL((url) => {- const m = url.pathname.match(/\/categories\/([^/]+)$/)- return !!m && m[1] !== 'new'- }, { timeout: 15_000 })- await page.waitForTimeout(2500)-- await gotoEdit(page, id)- await openChildrenModal(page)- const selected = await selectedNamesInModal(page)- expect(selected).not.toContain(removed)- const stillThere = children.find(c => c !== removed)- if (stillThere)- expect(selected).toContain(stillThere)- })-- test('edit: removing two children opens confirm dialog and applies on confirm', async ({ page }) => {- const { children, id } = await createParentWithChildren(page, 'confirm', 2)-- await gotoEdit(page, id)- await openChildrenModal(page)-- // Uncheck all selected (≥2)- const rows = candidateRows(page)- const total = await rows.count()- let unchecked = 0- for (let i = 0; i < total; i++) {- const row = rows.nth(i)- if (await row.getAttribute('aria-pressed') !== 'true')- continue- await row.click()- unchecked++- }- expect(unchecked).toBeGreaterThanOrEqual(2)-- await applyModal(page)-- const confirmBtn = page.getByRole('button', { name: T.confirm }).first()- await expect(confirmBtn).toBeVisible({ timeout: 5_000 })- await confirmBtn.dispatchEvent('click')-- await saveCategory(page)- await page.waitForURL((url) => {- const m = url.pathname.match(/\/categories\/([^/]+)$/)- return !!m && m[1] !== 'new'- }, { timeout: 15_000 })- await page.waitForTimeout(2500)-- await gotoEdit(page, id)- // After full removal there may be no children candidates / no row at all.- if (await page.getByText(T.childCategories).count() > 0) {- await openChildrenModal(page)- const selected = await selectedNamesInModal(page)- for (const original of children)- expect(selected).not.toContain(original)- }- })-- test('edit: cancelling confirm dialog reverts removal', async ({ page }) => {- const { children, id } = await createParentWithChildren(page, 'cancelConfirm', 2)-- await gotoEdit(page, id)- await openChildrenModal(page)-- // Uncheck all selected (≥2 → triggers confirm)- const rows = candidateRows(page)- const total = await rows.count()- for (let i = 0; i < total; i++) {- const row = rows.nth(i)- if (await row.getAttribute('aria-pressed') === 'true')- await row.click()- }-- await applyModal(page)-- const cancelBtn = page.getByRole('button', { name: T.cancel }).first()- await expect(cancelBtn).toBeVisible({ timeout: 5_000 })- await cancelBtn.dispatchEvent('click')-- // Children modal stays open; selection should revert to the original set.- await page.waitForTimeout(500)- const selected = await selectedNamesInModal(page)- for (const original of children)- expect(selected).toContain(original)- })-- test('children modal search filters candidate list', async ({ page }) => {- await page.goto('/categories/new')- await waitForCategoryFormReady(page)- await openChildrenModal(page)-- const rows = candidateRows(page)- const totalBefore = await rows.count()- expect(totalBefore).toBeGreaterThan(0)-- const firstName = await getCandidateName(rows.nth(0))- expect(firstName).not.toBe('')- const queryStem = firstName.slice(0, Math.min(3, firstName.length)).toLowerCase()-- await page.getByPlaceholder(T.search).fill(queryStem)- await page.waitForTimeout(300)-- const totalAfter = await candidateRows(page).count()- expect(totalAfter).toBeGreaterThan(0)- expect(totalAfter).toBeLessThanOrEqual(totalBefore)-- for (let i = 0; i < totalAfter; i++) {- const row = candidateRows(page).nth(i)- const haystack = ((await row.textContent()) ?? '').toLowerCase()- expect(haystack).toContain(queryStem)- }- })-- test('children modal search shows no-matches state', async ({ page }) => {- await page.goto('/categories/new')- await waitForCategoryFormReady(page)- await openChildrenModal(page)-- await page.getByPlaceholder(T.search).fill('zzzzzzz_no_such_category')- await page.waitForTimeout(300)-- expect(await candidateRows(page).count()).toBe(0)- })-- test('selecting a parent on /new hides Child categories row', async ({ page }) => {- await page.goto('/categories/new')- await waitForCategoryFormReady(page)- await expect(page.getByText(T.childCategories).first()).toBeVisible()-- await page.getByText(T.parentCategory).first().click()- // Bottom sheet shows a "Without parent" chip + the parent candidates list.- // Candidates render as clickable category rows (plain divs with @click, not- // links), so pick a seeded category by name (the click bubbles to the row).- const sheet = page.locator('.bottomSheetContent').last()- const candidate = sheet.getByText(/^E2E Category \d+$/).first()- await expect(candidate).toBeVisible({ timeout: 10_000 })- await candidate.click()-- await expect(page.getByText(T.childCategories)).toHaveCount(0)- })-})