super-productivity/e2e
Johannes Millan 88b5055504
fix(theme): tolerate work contexts persisted without a theme (#9139) (#9145)
* fix(theme): tolerate work contexts persisted without a theme (#9139)

A tag/project entity can be persisted with no `theme` at all. Validation
at hydration is non-fatal, so such a snapshot loads anyway and every
consumer then dereferences `undefined`, crashing the theme pipeline on
every launch. Reproduced end-to-end: resolveBackground() throws on
backgroundImageDark/Light and _setColorTheme() on isAutoContrast.

Two layers:

- resolveContextTheme() extracted from the currentTheme$ map, defaulting
  a missing theme to WORK_CONTEXT_DEFAULT_THEME. Single choke point for
  both crashing consumers. This also fixes the tag-colour branch, which
  spread an undefined theme into a partial `{ primary }` object.

- an auto-fix branch backfilling a missing tag/project theme, so data
  already corrupted on disk is healed rather than merely tolerated.
  Unrepaired, the same corruption also dead-ended legacy migration with
  "Migration failed" and no way in.

The auto-fix branch matches on path + `value === undefined` and
deliberately NOT on `error.expected`: typia reports this as the
generated name `Readonly<__type>.oNN`, whose ordinal shifts with the
type graph, so an expected-based guard would silently stop firing.

Verified: both fixes sabotage-tested (3 failures each with the fix
reverted), full suite green in both TZ variants, and confirmed firing
against real typia output and real hydration in the browser.

* fix(theme): address review findings on the #9139 theme fix

Follow-up to d6eee18bc0, from a multi-agent review.

- Heal system entities with their OWN theme. The backfill discarded the
  entity id and gave every entity the generic default, so TODAY -- the
  entity from the report -- came back purple with background tint on
  instead of cornflower/hue-400/tint-off, and INBOX lost its green. The
  repair is written to disk, so that restyle was permanent. Looked up via
  a Map, not an object literal, so a hostile `__proto__` id cannot resolve
  to Object.prototype.

- Repair `theme: null`, not just a missing theme. The `setOne` 'replace'
  branch applies a remote entity verbatim, so null is reachable and typia
  reports it at the same path; gating on `undefined` left it dead-ending
  the repair pipeline. resolveContextTheme already used `??`, so the two
  layers now agree.

- Guard the two remaining unguarded derefs. nav-list-tree renders once
  per project in the side nav and DEFAULT_PROJECT_ICON is not an emoji,
  so the theme branch is the DEFAULT path -- a theme-less project still
  crashed at launch, the very case the heal anticipates.

- Make both layers agree on the default: resolveContextTheme is now
  type-aware, so a theme-less project no longer renders tag-purple and
  then flips to project-teal once a repair runs.

- Scope the JSDoc's "single choke point" claim to currentTheme$, and
  correct RECREATE_FALLBACK's doc, which still said TAG/PROJECT had no
  heal branch. Added `theme` to their requiredKeys so the meta-reducer
  warn names it.

- Replaced two vacuous tests: one asserted an input typia cannot produce
  (every WorkContextThemeCfg field is optional, so the fixture was valid),
  the other's assertions passed on `null`.

Verified: all four new behaviours sabotage-tested, full suite green in
both TZ variants, and confirmed end-to-end that a theme-less TODAY tag
migrates and persists #6495ED/hue-400/tint-off rather than the default.

* fix(theme): share one default-theme source between read and heal

Follow-up to ba29dc62ac, from a second multi-agent review.

The previous commit fixed two review findings that turned out to
interact: it made the on-disk heal id-aware (so TODAY keeps its own
theme) and the read side only type-aware. Each was right alone; together
they reintroduced the very read/write divergence the type-awareness was
meant to remove, relocated from projects onto system entities. For a
theme-less TODAY -- the active context at startup, and the entity in the
report -- the read side rendered purple/hue-500/tinted while a later
repair persisted cornflower/hue-400/untinted. Not a flicker: hydration
validates without repairing, so a local-only user saw the wrong theme
indefinitely, then it flipped the first time a sync repair ran.

- extract getDefaultWorkContextTheme() into a leaf util both sides call,
  so the two cannot drift again. Net negative production lines.
- drop IN_PROGRESS_TAG from the lookup: its theme differs from
  DEFAULT_TAG's only in backgroundImageDark ('' vs null), which
  isBackgroundImageSet treats identically, so the row was provably inert.
  URGENT/IMPORTANT stay -- board.component's createTags() makes them
  user-reachable and their primaries do differ.
- drop 'theme' from RECREATE_FALLBACK requiredKeys: the recreate path
  already spreads defaults, so it only bought warn text at the cost of a
  four-clause doc paragraph.

Tests:
- replace the __proto__ test, which named __proto__ but used entity id
  't1' and so never entered the guarded branch -- unfalsifiable, and it
  survived sabotaging the Map into a plain object literal.
- buildCtx defaulted to id 'TODAY', quietly routing the generic-default
  cases through a system entity.
- table-driven system-entity coverage that asserts each row is
  DISTINGUISHABLE from the generic default, so an inert row fails rather
  than lingering.
- pin the branch's position in the else-if chain via its fix label.
- nav-list fixture now omits `icon`, the fall-through its comment claims.

Also scoped two over-claiming comments to what they actually guarantee,
including a KNOWN RESIDUAL for lwwUpdateMetaReducer's recreate branch --
a third, id-blind writer left alone deliberately as sync-critical.

Verified: shared-helper fix sabotage-tested, full suite green both TZ
variants (13195/13181), and the real bundle confirmed end-to-end -- no
circular import, migration succeeds, TODAY heals to #6495ED/hue-400.

* fix(theme): restore the recreate warn, make the inert-row guard real

Follow-up to c62b2eb88f, from a targeted review of that commit.

- restore 'theme' to RECREATE_FALLBACK TAG/PROJECT requiredKeys. Removing
  it was NOT behaviour-free as claimed: the warn is gated on
  `partialKeys.length > 0`, so a payload carrying title+taskIds and no
  theme now logged nothing at all -- the diagnostic vanished rather than
  merely dropping a field name. That is exactly the #9139 corruption
  shape, on lwwUpdateMetaReducer's recreate branch, the one writer still
  bypassing getDefaultWorkContextTheme. With provenance unknown that is
  the wrong signal to delete. Now pinned by a test, since the entry looks
  removable and I removed it once already.

  My verification was a level too shallow: I confirmed requiredKeys "only
  feeds the warn" and stopped, without checking the warn is gated on the
  list being non-empty.

- make the system-entity table test actually do what it claimed. It was a
  hand-written duplicate of SYSTEM_ENTITY_THEMES, so it caught rows
  REMOVED from the Map but never rows ADDED -- re-adding the inert
  IN_PROGRESS_TAG row left the suite green. Now driven from the Map's own
  entries, and comparing OBSERVABLE difference: the background-image
  fields reach the UI only via isBackgroundImageSet, so '' and null are
  the same thing. My first attempt at this compared raw fields and was
  weaker still -- it let the inert row pass. Verified by sabotage: the
  re-added row now fails.

- __proto__ test built via JSON.parse, the only construction that yields
  a genuine own key and what a hostile payload actually arrives as. The
  previous comment claimed the opposite of what its line did:
  `obj['__proto__'] = x` invokes the inherited setter and creates no own
  property.

- scope two more over-claiming comments: the shared fallback guarantees
  agreement on the FALLBACK, not on the tag-color override layered above
  it (read-side only, re-applied after any repair); and the label
  assertion cannot detect what its comment described.

- getDefaultWorkContextTheme takes WorkContextType rather than a boolean.

Verified: every fix sabotage-tested, full suite green both TZ variants
(13200/13186), lint clean.

* test(theme): pin the currentTheme$ wiring and the system-theme roster

The #9139 fix could be reverted at its only production integration point
with the suite green: resolveContextTheme was tested exhaustively as a pure
function, but nothing asserted currentTheme$ actually calls it. Replacing
map(resolveContextTheme) with the pre-fix map((awc) => awc.theme) passed
32/32. Adds a MockStore test driving a themeless TODAY through the real
stream, which is what every crashing consumer reads.

Also pins the SYSTEM_ENTITY_THEMES roster. The existing cases are driven
from the Map itself so an added row is covered automatically, but that is
blind to removal - deleting rows deletes their tests, which vanish rather
than fail. URGENT and IMPORTANT were removable undetected across both
suites. Both halves are needed; neither catches what the other does.

Sabotage-verified: each new test fails under the mutation it targets.

* fix(theme): copy the theme fallback and pin the PROJECT recreate warn

resolveContextTheme handed out the module constant itself on the fallback
path (DEFAULT_TAG.theme, TODAY_TAG.theme, ...). Nothing freezes those, so a
consumer mutating what it was handed would write through into the shared
constant app-wide. The on-disk heal already spreads for exactly this reason;
only the read side was aliased. Spread there too and assert non-aliasing, so
the invariant is enforced rather than just documented. Free for the stream:
currentTheme$ dedups via isShallowEqual, which is key-by-key.

Also parameterizes the recreate warn test over PROJECT as well as TAG.
RECREATE_FALLBACK.PROJECT's 'theme' entry was dead - dropping it passed
133/133 - so a diagnostic the fix depends on could be removed with nothing
going red.

Sabotage-verified: removing the spread fails 6 tests; dropping either
requiredKeys entry now fails one.

* test(theme): drive the #9139 heal with REAL typia validation

Every existing case hand-builds its typia errors, so all of them would pass
even if real typia reported a themeless entity somewhere the fix's branch
never matches. #9045 shipped exactly that: a fully tested check that never
fired in production.

Runs the actual validator instead. Confirms real typia reports a missing
theme at $input.<root>.entities.<id>.theme with an undefined value (and null
identically), which is precisely what the branch keys on, and round-trips
the repair back through validation to prove the written value is accepted.

Also pins the #9156 gap as characterization: every member of
WorkContextThemeCfg is optional, so typia accepts theme={} and even a theme
missing primary. No error is produced, so neither the heal nor the read-side
?? can ever see them - an empty theme is stickier than a missing one. Those
expectations should flip when #9156 is fixed.

Sabotage-verified: changing the branch gate to keys.length === 5, i.e. a
branch that never fires on real data, fails 9 tests.

* test(theme): add an E2E proving the app boots with a themeless TODAY tag

The unit tests pin the fallback, the heal and the currentTheme$ wiring, but
none of them can show the app actually STARTS with this data on disk, which
is the only claim #9139 makes. Seeds a legacy store whose TODAY tag has no
theme, then asserts migration completes, the shell renders, no theme-related
uncaught error fires, and the tag is HEALED on disk rather than merely
tolerated at read time.

Mutates the existing fixture in-code instead of committing a near-duplicate
100KB JSON, so the one deleted key stays visible in the diff.

Sabotage-verified, and the result bounded the test's scope: disabling the
heal fails it (TODAY does not survive migration at all), while removing the
read-side fallback leaves it GREEN - with the heal in place the data is
repaired before the read side is reached. So this covers the heal only; the
read side stays covered by the currentTheme$ unit test. Documented in the
spec header so nobody assumes broader coverage than it has.

* test(theme): cover the read-side fallback with a hydration E2E

The migration E2E only exercises the on-disk heal: with the heal in place the
data is repaired before the read side is ever reached, so removing the
fallback left it green. But #9139 was reported on an ordinary launch, not a
migration - hydration validates without repairing, so resolveContextTheme is
the only thing between the user and the crash on that path.

Adds a second test that corrupts an ALREADY-migrated store and relaunches.
Sabotage matrix now covers both defenses independently: disabling the heal
fails test 1, removing the read-side fallback fails test 2, each solo.

Two things this cost that are worth knowing:
- state_cache uses an in-line keyPath, so put(row, 'current') raises DataError
  and ABORTS the transaction rather than erroring - it surfaces as a 30s hang
  and a misleading 'execution context was destroyed'. Every IndexedDB request
  here has onblocked/onerror/onabort and a JS-side timeout so a failure names
  itself instead of looking like every other failure.
- Asserting 'no page errors' right after the side nav appears FALSE-PASSES:
  the shell renders before the theme pipeline throws. Caught because the
  sabotaged run failed alongside its sibling but passed solo. Both tests now
  wait for something real first and assert errors last, without a bare
  waitForTimeout (forbidden by e2e/CLAUDE.md).

Note TODAY membership is virtual (dueDay), so a fixture's TODAY.taskIds alone
renders an empty list - test 1 settles on an IndexedDB read instead.
2026-07-18 21:37:56 +02:00
..
constants chore(ui): removes dead components and features [#8260 - Tier A] (#8889) 2026-07-10 11:40:35 +02:00
electron fix(sync): isolate provider encryption settings + enforce critical e2e coverage (#9044) 2026-07-15 14:24:49 +02:00
fixtures test(e2e): dismiss devError native dialogs so sync tests don't hang 2026-05-23 23:13:09 +02:00
helpers fix(sync): isolate provider encryption settings + enforce critical e2e coverage (#9044) 2026-07-15 14:24:49 +02:00
pages test(project): guard project navigation route detection (#9103) 2026-07-17 11:59:08 +02:00
store-screenshots feat(focus-mode): make preparation opt-in, smooth start transition (#8639) 2026-06-29 19:44:53 +02:00
store-video feat(tasks): redesign add-task-bar layout, toggles, note field & a11y (#8812) 2026-07-07 16:26:36 +02:00
tests fix(theme): tolerate work contexts persisted without a theme (#9139) (#9145) 2026-07-18 21:37:56 +02:00
utils test(e2e): accept beforeunload prompt in shared dialog fallback (#9122) 2026-07-17 17:34:29 +02:00
.gitignore fix(gitignore): correct screenshots directory path in .gitignore 2026-01-21 21:05:29 +01:00
CLAUDE.md docs: trim CLAUDE.md and split E2E reference into e2e/CLAUDE.md 2026-05-01 23:04:03 +02:00
global-setup.ts test(e2e): harden failure signals and provider gates (#7753) 2026-05-23 20:33:04 +02:00
playwright.config.ts test(e2e): harden failure signals and provider gates (#7753) 2026-05-23 20:33:04 +02:00
playwright.store-screenshots.config.ts test(screenshots): stabilize electron screenshot output 2026-05-09 14:38:49 +02:00
playwright.store-screenshots.electron.config.ts test(screenshots): stabilize electron screenshot output 2026-05-09 14:38:49 +02:00
playwright.store-video.config.ts feat(video): Playwright-driven marketing reel pipeline 2026-05-07 23:08:24 +02:00
README.md chore(ui): removes dead utilities and op-log leftovers [#8260 - Tier A] (#8892) 2026-07-11 13:05:34 +02:00
tsconfig.json refactor: move tests 2025-08-02 11:37:25 +02:00

E2E Testing Guide for Super Productivity

This guide provides comprehensive information for writing and maintaining end-to-end tests for Super Productivity using Playwright.

Table of Contents


Overview

Our E2E tests are built with Playwright and follow the Page Object Model (POM) pattern for maintainability and reusability. Tests are organized by feature and use shared fixtures for common setup.

Key Technologies

  • Playwright: Modern E2E testing framework
  • TypeScript: Type-safe test code
  • Page Object Model: Encapsulates page interactions
  • Fixtures: Shared setup and utilities

Running Tests

Basic Commands

# Run all tests
npm run e2e

# Run tests in UI mode (interactive)
npm run e2e:ui

# Run a single test file with detailed output
npm run e2e:file tests/task-basic/task-crud.spec.ts

# Run tests in headed mode (see browser)
npm run e2e:headed

# Run tests in debug mode
npm run e2e:debug

# Show test report
npm run e2e:show-report

WebDAV Sync Tests

# Run WebDAV tests (starts Docker container)
npm run e2e:webdav

Test Structure

Directory Layout

e2e/
├── constants/          # Shared selectors and constants
│   └── selectors.ts    # Centralized CSS selectors
├── fixtures/           # Test fixtures and setup
│   └── test.fixture.ts # Custom test fixtures with page objects
├── helpers/            # Test helper functions
│   └── plugin-test.helpers.ts
├── pages/              # Page Object Models
│   ├── base.page.ts    # Base page with common methods
│   ├── work-view.page.ts
│   ├── project.page.ts
│   ├── task.page.ts
│   ├── settings.page.ts
│   ├── dialog.page.ts
│   ├── planner.page.ts
│   ├── side-nav.page.ts
│   ├── sync.page.ts
│   ├── tag.page.ts
│   └── note.page.ts
├── tests/              # Test specifications
│   ├── task-basic/
│   ├── project/
│   ├── planner/
│   └── ...
├── utils/              # Utility functions
│   ├── waits.ts        # Wait helpers
│   └── sync-helpers.ts
├── playwright.config.ts
└── global-setup.ts

Page Objects

Page Objects encapsulate interactions with specific pages or components. All page objects extend BasePage and receive a page and optional testPrefix.

Available Page Objects

1. BasePage (base.page.ts)

Base class for all page objects. Provides common functionality:

class BasePage {
  async addTask(taskName: string): Promise<void>;
  // Adds a task with automatic test prefix
}

Example:

await workViewPage.addTask('My Task');
// Creates task with name "W0-P0-My Task" (prefixed for isolation)

2. WorkViewPage (work-view.page.ts)

Interactions with the main work view:

class WorkViewPage extends BasePage {
  async waitForTaskList(): Promise<void>;
  async addSubTask(task: Locator, subTaskName: string): Promise<void>;
}

Example:

await workViewPage.waitForTaskList();
await workViewPage.addTask('Parent Task');
const task = page.locator('task').first();
await workViewPage.addSubTask(task, 'Child Task');

3. TaskPage (task.page.ts)

Task-specific operations:

class TaskPage extends BasePage {
  getTask(index: number): Locator;
  getTaskByText(text: string): Locator;
  async markTaskAsDone(task: Locator): Promise<void>;
  async editTaskTitle(task: Locator, newTitle: string): Promise<void>;
  async openTaskDetail(task: Locator): Promise<void>;
  async getTaskCount(): Promise<number>;
  async isTaskDone(task: Locator): Promise<boolean>;
  getDoneTasks(): Locator;
  getUndoneTasks(): Locator;
  async waitForTaskWithText(text: string): Promise<Locator>;
  async taskHasTag(task: Locator, tagName: string): Promise<boolean>;
}

Example:

const task = taskPage.getTask(1); // First task
await taskPage.markTaskAsDone(task);
await expect(taskPage.getDoneTasks()).toHaveCount(1);

4. ProjectPage (project.page.ts)

Project management:

class ProjectPage extends BasePage {
  async createProject(projectName: string): Promise<void>;
  async navigateToProjectByName(projectName: string): Promise<void>;
  async createAndGoToTestProject(): Promise<void>;
  async addNote(noteContent: string): Promise<void>;
  async archiveDoneTasks(): Promise<void>;
}

Example:

await projectPage.createProject('My Project');
await projectPage.navigateToProjectByName('My Project');
await projectPage.addNote('Project notes here');

5. SettingsPage (settings.page.ts)

Settings and configuration:

class SettingsPage extends BasePage {
  async navigateToSettings(): Promise<void>;
  async expandSection(sectionSelector: string): Promise<void>;
  async expandPluginSection(): Promise<void>;
  async navigateToPluginSettings(): Promise<void>;
  async enablePlugin(pluginName: string): Promise<boolean>;
  async disablePlugin(pluginName: string): Promise<boolean>;
  async isPluginEnabled(pluginName: string): Promise<boolean>;
  async uploadPlugin(pluginPath: string): Promise<void>;
}

Example:

await settingsPage.navigateToPluginSettings();
await settingsPage.enablePlugin('Test Plugin');
expect(await settingsPage.isPluginEnabled('Test Plugin')).toBeTruthy();

6. DialogPage (dialog.page.ts)

Dialog and modal interactions:

class DialogPage extends BasePage {
  async waitForDialog(): Promise<Locator>;
  async waitForDialogToClose(): Promise<void>;
  async clickDialogButton(buttonText: string): Promise<void>;
  async clickSaveButton(): Promise<void>;
  async fillDialogInput(selector: string, value: string): Promise<void>;
  async fillMarkdownDialog(content: string): Promise<void>;
  async saveMarkdownDialog(): Promise<void>;
  async editDateTime(dateValue?: string, timeValue?: string): Promise<void>;
}

Example:

await dialogPage.waitForDialog();
await dialogPage.fillDialogInput('input[name="title"]', 'New Title');
await dialogPage.clickSaveButton();
await dialogPage.waitForDialogToClose();

Common Patterns

Pattern 1: Basic Task CRUD

test('should create and edit task', async ({ page, workViewPage, taskPage }) => {
  await workViewPage.waitForTaskList();

  // Create
  await workViewPage.addTask('Test Task');
  await expect(taskPage.getAllTasks()).toHaveCount(1);

  // Edit
  const task = taskPage.getTask(1);
  await taskPage.editTaskTitle(task, 'Updated Task');
  await expect(taskPage.getTaskTitle(task)).toContainText('Updated Task');

  // Mark as done
  await taskPage.markTaskAsDone(task);
  await expect(taskPage.getDoneTasks()).toHaveCount(1);
});

Pattern 2: Project Workflow

test('should create project and add tasks', async ({ projectPage, workViewPage }) => {
  await projectPage.createAndGoToTestProject();
  await workViewPage.addTask('Project Task 1');
  await workViewPage.addTask('Project Task 2');
  await expect(page.locator('task')).toHaveCount(2);
});

Pattern 3: Settings Configuration

test('should enable plugin', async ({ settingsPage, waitForNav }) => {
  await settingsPage.navigateToPluginSettings();
  await settingsPage.enablePlugin('My Plugin');
  await waitForNav();
  expect(await settingsPage.isPluginEnabled('My Plugin')).toBeTruthy();
});

Pattern 4: Dialog Interactions

test('should edit date in dialog', async ({ taskPage, dialogPage }) => {
  const task = taskPage.getTask(1);
  await taskPage.openTaskDetail(task);

  const dateInfo = dialogPage.getDateInfo('Created');
  await dateInfo.click();
  await dialogPage.editDateTime('12/25/2025', undefined);
  await dialogPage.clickSaveButton();
});

Selectors

All selectors are centralized in constants/selectors.ts. Always use these constants instead of hardcoding selectors in tests.

Using Selectors

import { cssSelectors } from '../constants/selectors';

const { TASK, TASK_TITLE, TASK_DONE_BTN } = cssSelectors;

// In test:
const task = page.locator(TASK).first();
const title = task.locator(TASK_TITLE);

Selector Categories

  • Navigation: SIDENAV, NAV_ITEM, SETTINGS_BTN
  • Layout: ROUTE_WRAPPER, BACKDROP, PAGE_TITLE
  • Tasks: TASK, TASK_TITLE, TASK_DONE_BTN, SUB_TASK
  • Add Task: ADD_TASK_INPUT, ADD_TASK_SUBMIT
  • Dialogs: MAT_DIALOG, DIALOG_FULLSCREEN_MARKDOWN
  • Settings: PAGE_SETTINGS, PLUGIN_SECTION, PLUGIN_MANAGEMENT
  • Projects: PAGE_PROJECT, CREATE_PROJECT_BTN, WORK_CONTEXT_MENU

Wait Utilities

Located in utils/waits.ts, these utilities help handle Angular's async nature.

Available Wait Functions

waitForAngularStability(page, timeout?)

Waits for Angular to finish all async operations.

await waitForAngularStability(page);

waitForAppReady(page, options?)

Comprehensive wait for app initialization.

await waitForAppReady(page, {
  selector: 'task-list',
  ensureRoute: true,
  routeRegex: /#\/project\/\w+/,
});

waitForStatePersistence(page)

Waits for IndexedDB persistence to complete (important before sync operations).

await workViewPage.addTask('Task');
await waitForStatePersistence(page); // Ensure saved to IndexedDB
// Now safe to trigger sync

Writing New Tests

Step 1: Create Test File

// e2e/tests/my-feature/my-feature.spec.ts
import { test, expect } from '../../fixtures/test.fixture';

test.describe('My Feature', () => {
  test('should do something', async ({ page, workViewPage, taskPage }) => {
    // Test code here
  });
});

Step 2: Use Page Objects

test('my test', async ({ workViewPage, taskPage, dialogPage }) => {
  // Wait for page ready
  await workViewPage.waitForTaskList();

  // Use page objects for interactions
  await workViewPage.addTask('Task 1');
  const task = taskPage.getTask(1);
  await taskPage.markTaskAsDone(task);

  // Assertions
  await expect(taskPage.getDoneTasks()).toHaveCount(1);
});

Step 3: Handle Waits Properly

// GOOD: Use Angular stability waits
await workViewPage.addTask('Task');
await waitForAngularStability(page);
await expect(page.locator('task')).toBeVisible();

// BAD: Arbitrary timeouts
await page.waitForTimeout(5000); // Avoid unless necessary

Step 4: Use Selectors from Constants

import { cssSelectors } from '../../constants/selectors';

const { TASK, TASK_TITLE } = cssSelectors;
const title = page.locator(TASK).first().locator(TASK_TITLE);

Best Practices

DO

  1. Use page objects for all interactions
  2. Use centralized selectors from constants/selectors.ts
  3. Wait for Angular stability after state changes
  4. Use test prefixes (automatic via fixtures) for isolation
  5. Test one thing per test - keep tests focused
  6. Use descriptive test names - "should create task and mark as done"
  7. Clean up state - tests should be independent
  8. Use role-based selectors when possible (accessibility)
// GOOD
await page.getByRole('button', { name: 'Save' }).click();

// LESS GOOD
await page.locator('.save-btn').click();

DON'T

  1. Don't hardcode selectors - use cssSelectors
  2. Don't use arbitrary waits - use waitForAngularStability
  3. Don't share state between tests - each test should be independent
  4. Don't access DOM directly - use page objects
  5. Don't skip error handling - tests should fail clearly
  6. Don't use any types - maintain type safety

Test Isolation

Each test gets:

  • Isolated browser context (clean storage)
  • Unique test prefix (W0-P0-, W1-P0-, etc.)
  • Fresh page instance

This ensures tests don't interfere with each other.

Handling Flakiness

// Use waitFor with explicit conditions
await page.waitForFunction(() => document.querySelectorAll('task').length === 3, {
  timeout: 10000,
});

// Use locator assertions (auto-retry)
await expect(page.locator('task')).toHaveCount(3);

// Avoid fixed timeouts
await page.waitForTimeout(1000); // BAD
await waitForAngularStability(page); // GOOD

Troubleshooting

Test Fails with "Element not found"

  1. Check if selector is correct in constants/selectors.ts
  2. Add wait before interaction: await waitForAngularStability(page)
  3. Use await element.waitFor({ state: 'visible' })
  4. Check if element is in a different context (iframe, shadow DOM)

Test Timeout

  1. Increase timeout in specific waitFor calls
  2. Check if Angular is stuck - look for pending HTTP requests
  3. Use page.pause() to debug interactively
  4. Check network tab for failed requests

Flaky Tests

  1. Add proper waits: waitForAngularStability, waitForAppReady
  2. Avoid page.waitForTimeout() - use condition-based waits
  3. Check for race conditions - ensure state is persisted
  4. Use waitForStatePersistence before operations that depend on saved state

Debugging

// Pause execution and open Playwright Inspector
await page.pause();

// Take screenshot
await page.screenshot({ path: 'debug.png' });

// Console log page content
console.log(await page.content());

// Get element text for debugging
const text = await page.locator('task').first().textContent();
console.log('Task text:', text);

Running Single Test

# Run specific file
npm run e2e:file tests/task-basic/task-crud.spec.ts

# Run in debug mode
npm run e2e:debug

# Run in headed mode to see browser
npm run e2e:headed

Examples

Example 1: Full Task CRUD Test

import { test, expect } from '../../fixtures/test.fixture';

test.describe('Task CRUD', () => {
  test('should create, edit, and delete tasks', async ({
    page,
    workViewPage,
    taskPage,
  }) => {
    await workViewPage.waitForTaskList();

    // Create
    await workViewPage.addTask('Task 1');
    await workViewPage.addTask('Task 2');
    await expect(taskPage.getAllTasks()).toHaveCount(2);

    // Edit
    const firstTask = taskPage.getTask(1);
    await taskPage.editTaskTitle(firstTask, 'Updated Task');
    await expect(taskPage.getTaskTitle(firstTask)).toContainText('Updated Task');

    // Mark as done
    await taskPage.markTaskAsDone(firstTask);
    await expect(taskPage.getDoneTasks()).toHaveCount(1);
    await expect(taskPage.getUndoneTasks()).toHaveCount(1);
  });
});

Example 2: Project Workflow

test('should create project with tasks', async ({
  projectPage,
  workViewPage,
  taskPage,
}) => {
  await projectPage.createAndGoToTestProject();

  await workViewPage.addTask('Project Task');
  await projectPage.addNote('Important notes');

  const task = taskPage.getTask(1);
  await taskPage.markTaskAsDone(task);

  await projectPage.archiveDoneTasks();
  await expect(taskPage.getUndoneTasks()).toHaveCount(0);
});

Example 3: Settings Test

test('should configure plugin', async ({ settingsPage, page }) => {
  await settingsPage.navigateToPluginSettings();

  const pluginExists = await settingsPage.pluginExists('Test Plugin');
  expect(pluginExists).toBeTruthy();

  await settingsPage.enablePlugin('Test Plugin');
  expect(await settingsPage.isPluginEnabled('Test Plugin')).toBeTruthy();

  await settingsPage.navigateBackToWorkView();
  await expect(page).toHaveURL(/tag\/TODAY/);
});

Getting Help

  • Check existing tests in e2e/tests/ for examples
  • Review page objects in e2e/pages/ for available methods
  • Look at constants/selectors.ts for available selectors
  • Use Playwright Inspector (npm run e2e:debug) for debugging
  • Check Playwright docs: https://playwright.dev/

Summary Checklist

When writing a new test:

  • Create test file in appropriate tests/ subdirectory
  • Import test and expect from fixtures/test.fixture.ts
  • Use page objects for all interactions
  • Use selectors from constants/selectors.ts
  • Add proper waits (waitForAngularStability, etc.)
  • Use descriptive test names
  • Ensure test is isolated (no shared state)
  • Run test locally before committing
  • Test passes consistently (run 3+ times)