super-productivity/e2e
Johannes Millan 3ae246d030
Feat/issue 7362 9d46d3 (#7363)
* test(e2e): open attachment dialog via detail panel after #7314

The attach-dialog entry point moved out of the task context menu in
PR #7314 and now lives in the detail panel. Update the WebDAV sync
attachment test to use openTaskDetailPanel() and click the attachment
input-item instead of right-clicking and looking for an "Attach" menu
item that no longer exists.

* refactor(tasks): drop dead addAttachment from task context menu

Leftover from #7314, which moved the attach dialog into the detail
panel. The method, its TaskAttachmentService injection, and the
DialogEditTaskAttachmentComponent import are unreachable from the
template.

* fix(api): reject inherited fields when creating subtask via REST

POST /tasks with parentId silently dropped any supplied projectId/tagIds
(the reducer forces tagIds=[] and projectId=parent.projectId), so callers
got 201 with values different from what they sent. Reject the request
with 400 UNSUPPORTED_FIELD instead, symmetric with how subTaskIds and
parentId-on-PATCH are handled.

* refactor(simple-counter): inline countdown wrapper, document set invariant

Inline the single-call-site `_hasStartedRepeatedCountdown` private wrapper.
Promote the `setCountdownRemaining` invariant note to JSDoc so it surfaces
in IDE tooltips at every call site — paused-display is gated by
`hasStartedCountdown`, and writing through `setCountdownRemaining` without
a prior `startCountdown` call would silently leave the value invisible.

* ci(plugins): run unit tests when plugin code changes

New workflow runs each plugin's `npm test` in a parallel matrix when
its directory or a shared package (plugin-api, vite-plugin) changes
on a PR. Detects per-plugin changes via three-dot `git diff` against
the PR base.

* fix(sync): break iOS WebDAV conflict-dialog loop (#7339)

Two compounding bugs trapped iOS WebDAV users in a per-minute conflict
dialog that no button could resolve:

1. FileBasedSyncAdapter's snapshotReplacement heuristic re-fires
   gapDetected on every sync from a non-writing client (clientId \!=
   excludeClient is true forever), so the download keeps coming back
   with snapshotState and OperationLogSyncService keeps throwing
   LocalDataConflictError despite the local clock already dominating
   the remote snapshot. Skip hydration and conflict when
   compareVectorClocks(local, remote) is EQUAL or GREATER_THAN, gated
   on both clocks being non-empty so a fresh client still hydrates a
   legacy/clockless snapshot.

2. SyncWrapperService._openConflictDialog$ filtered undefined out of
   the afterClosed() stream, so a programmatic close (iOS WebView
   lifecycle, re-entry) collapsed the observable and firstValueFrom
   threw EmptyError — the user's Use Local/Use Remote/Cancel click
   never reached the resolution branches. Drop the filter so undefined
   flows through to the existing cancellation path.

The dominate-skip deliberately does NOT append result.newOps to the
op log: VectorClockService.getEntityFrontier is last-write-wins by
seq, and writing historical remote ops at the current tail would
regress per-entity frontiers and let future LWW resolution overwrite
local data. Trade-off documented inline.

Adds an adapter-level integration reproducer that asserts gapDetected
re-fires forever for a non-writing client (the upstream loop trigger),
a 3-client WebDAV e2e that reproduces the loop end-to-end against a
real provider, plus service-level tests for the dominate-skip, the
empty-clock guard, the concurrent-clock conservative path, and
consecutive-sync loop prevention.

* fix(sync): improve Dropbox auth dialog UX on sandboxed Linux (#7139)

The "Get Authorization Code" button silently failed on Flatpak because
shell.openExternal rejects without renderer feedback when the
org.freedesktop.portal.Desktop talk-name isn't granted. After the user
gave up and reopened the dialog, the second attempt failed again with
`invalid_grant: invalid code verifier` because each call to
Dropbox.getAuthHelper() generated a fresh PKCE verifier that no longer
matched the originally-shown URL's challenge.

Three changes:

- Cache the in-flight PKCE Promise on the Dropbox provider so concurrent
  callers and consecutive dialog opens share one verifier+URL pair.
  Cleared on successful exchange, on clearAuthCredentials(), and on a
  rejected generation (so a one-time crypto failure doesn't poison the
  session). Five regression tests cover reuse, success-clear, explicit
  clear, concurrent calls, and rejection-recovery.

- Render the auth URL as user-selectable text under a <details>
  disclosure. Escape hatch when both shell.openExternal and the
  clipboard portal are denied — the user can triple-click to select and
  Ctrl+C the URL into a manually-opened browser. Adds
  D_AUTH_CODE.MANUAL_URL_HINT translation key.

- Pipe shell.openExternal rejections through
  errorHandlerWithFrontendInform so the existing IPC.ERROR snack
  channel surfaces a "Could not open the link in your browser" message
  instead of swallowing the failure to electron-log. Wrapped in a
  try/catch since errorHandlerWithFrontendInform throws synchronously
  if the renderer isn't ready.

The Flathub manifest also needs --talk-name=org.freedesktop.portal.Desktop
and --socket=wayland to fully fix the user-reported issue, but that
change lives in the flathub repo.

* refactor(sync): rename dialog-sync-initial-cfg to dialog-sync-cfg

Pure rename — no behavior change. The component is the canonical sync
config dialog, used both for first-time setup and editing. The "Initial"
qualifier was misleading once it became the only sync-config surface
(see #7362).

* refactor(sync): consolidate sync actions into the sync dialog

Move Re-authenticate, Force overwrite, and Restore from history into
DialogSyncCfgComponent so the dialog is the canonical surface for sync
configuration and management.

- Re-authenticate (OAuth providers, currently Dropbox) shown inline
  when the active provider has getAuthHelper() and is already authed.
  Bypasses the dirty-form gate so credentials can refresh without
  losing in-progress edits.
- Force overwrite and Restore from history live in a new "Advanced"
  section gated on isWasEnabled() (existing config) and disabled when
  the form is dirty with a "Save changes first" tooltip. Restore stays
  SuperSync-only.
- Force overwrite reuses the existing native confirm in
  SyncWrapperService.forceUpload() — no extra confirmation dialog to
  avoid double-confirm on the other 5 internal callers.

The legacy buttons on the settings page are removed in a follow-up
commit.

Refs #7362

* refactor(sync): move WebDAV Test Connection button into the sync dialog

Test Connection was previously injected into the inline sync form on
the settings page. It needs to live wherever the sync form is
rendered. The next commit removes the inline form, so move the
injection into DialogSyncCfgComponent first.

No user-visible change: the button still appears in the WebDAV
section of the sync form, just sourced from the dialog component now.

* refactor(config-page): replace inline sync form with status row + buttons

The Sync & Backup tab now hosts a compact status surface, not a full
form clone:

- When sync is disabled or unconfigured: empty-state hint + "Set up
  sync" primary button.
- When configured: provider name, optional "Authentication required"
  pill (OAuth providers) and "Encrypted" pill, then "Sync now" primary
  button + "Configure" secondary button.

The dialog is the canonical sync config surface — reachable from this
tab, the header sync icon (right-click / long-press), or
SyncWrapperService when first-time setup is needed. Force overwrite
and Restore from history live inside the dialog now (see prior commit).

Removes _buildSyncFormConfig (~250 lines of formly button injection),
the empty authStatus placeholder field in SYNC_FORM, and the unused
tour-syncSection class.

Refs #7362

* refactor(sync): consolidate BTN_FORCE_OVERWRITE translation key

The SUPER_SYNC.BTN_FORCE_OVERWRITE key was a duplicate with no
consumers — its English copy ("Force Overwrite Server") even drifted
from the canonical F.SYNC.S.BTN_FORCE_OVERWRITE ("Force Overwrite").

The third occurrence under D_ENTER_PASSWORD ("Use Local Data") stays
— that's a different conflict-resolution action, not a duplicate.

Refs #7362

* refactor(sync): simplify sync dialog — collapse advanced fields, kebab menu

The previous "Advanced" zone (hr + heading + hint + button stack) plus
always-visible interval/manual-only/compression toggles made the dialog
visually noisy. Two changes:

- Move syncInterval and isManualSyncOnly into the existing
  "Advanced Config" collapsible alongside compression. The collapsible
  is hidden for SuperSync (which uses fixed settings) — most users
  never need to expand it.
- Move Force overwrite + Restore from history out of the dialog body
  into a kebab (more_vert) menu in the dialog title row. They act on
  saved config — the kebab placement makes that scope clear and removes
  the dirty-form gate / "Save changes first" ambiguity.

The kebab is hidden during first-time setup (gated on isWasEnabled).
The Re-authenticate button stays inline as before.

Drops three translation keys added in the prior commit (ADVANCED,
ADVANCED_HINT, SAVE_FIRST_HINT) — no longer referenced.

Refs #7362

* fix(sync): drop primary color from Cancel button in sync dialog

Cancel is a secondary action; only the affirmative button (Save)
should carry the primary color.

* fix(sync): clarify Dropbox info text for the new dialog flow

The previous copy said "Click the button below to authenticate" — but
in the consolidated dialog there is no inline Authenticate button for
first-time setup; OAuth runs as part of Save. Make the copy describe
the actual flow instead of pointing at a button that no longer exists.

* refactor(sync): move Force overwrite + Restore into the Advanced collapsible

The kebab menu introduced earlier hid Force overwrite and Restore from
history behind a small icon and required users to know that "more_vert"
in the dialog title contained sync actions. Fold them into the existing
top-level collapsible instead — the same one that already hosts sync
interval, manual-only, and compression toggles.

- Rename the collapsible's label from "Advanced Config" to "Advanced"
  via a new sync-specific translation key (the global ADVANCED_CFG key
  is shared with issue providers, so we don't touch it).
- The dialog component appends Force overwrite (warn) and Restore from
  history (SuperSync only) to the collapsible's fieldGroup in edit
  mode. First-time setup keeps the original SuperSync hide so the
  collapsible never appears empty.

Re-authenticate stays as an inline button below the form because its
visibility depends on an async provider.isReady() check that doesn't
fit Formly's sync hideExpression.

Refs #7362

* refactor(sync): single Advanced collapsible per provider, all actions inside

Each provider now has exactly one "Advanced" collapsible:
- non-SuperSync: top-level (interval, manual-only, compression,
  enable-encryption, plus injected Re-authenticate / Force overwrite
  in edit mode)
- SuperSync: nested in the SuperSync section (server URL, plus injected
  Force overwrite / Restore from history in edit mode)

The inner SuperSync collapsible's label switches from "Advanced Config"
to "Advanced" so both surfaces read the same. Re-authenticate moves
from a button below the form into the non-SuperSync Advanced collapsible
as a Formly button gated on `syncProvider === Dropbox`. Drops the async
provider.isReady() check — re-auth is shown for Dropbox in edit mode
regardless, since `force=true` works for both stale-token and switching
accounts.

Honors the rule that no buttons sit below the Advanced collapsible
inside the dialog.

Refs #7362

* refactor(sync): use stroked style for all dialog buttons + add Nextcloud test

- Every action button inside the sync dialog now uses btnStyle: 'stroked'
  for a consistent outlined appearance: Re-authenticate, Force overwrite,
  Restore from history, WebDAV/Nextcloud Test connection, file-based and
  SuperSync Enable encryption, SuperSync Get token, LocalFile folder
  pickers.
- Force overwrite keeps btnType: 'warn' so it stays warn-coloured but as
  an outline rather than a filled warn button.
- The conditional stroked-when-token-set toggle on Get token is dropped
  in favour of always-stroked.
- Re-authenticate and Restore previously misused btnType: 'stroked' (a
  color slot) instead of btnStyle: 'stroked' (the actual style flag) —
  the formly-btn template ignored the unrecognised color, so they
  rendered as filled buttons. Fixed.
- Adds a Test Connection button to the Nextcloud section, matching the
  WebDAV one — Nextcloud's serverUrl + userName are translated into the
  WebDAV-shaped baseUrl client-side before invoking WebdavApi.testConnection.

Refs #7362

* refactor(sync): apply multi-review fixes — fragility, races, dedup, lifecycle

Cross-validated findings from the multi-agent review:

**Correctness / lifecycle**
- `fields` becomes a `computed` signal of `_getFields(isWasEnabled())`,
  removing the manual `fields.set()` re-sync after the enabled flag
  flips. Single source of truth.
- Reset `_tmpUpdatedCfg._isInitialSetup = false` when the dialog opens
  in edit mode so SuperSync encryption-warning hideExpressions stop
  treating returning users as first-timers.
- Replace ad-hoc `Subscription` aggregator with `takeUntilDestroyed` on
  both subscriptions in the dialog component.

**Race conditions**
- `syncSettingsForm$` subscription on the settings page now goes through
  `switchMap` so a fresh emission cancels any in-flight `provider.isReady()`
  probe — late callbacks can no longer overwrite newer state.
- Drop the redundant `_cd.markForCheck()` after `signal.set()` — signals
  integrate with OnPush automatically.
- Use `??` instead of `||` when preserving `globalCfg` flags during
  provider switch, so an explicit `false` is honoured.

**De-duplication**
- Promote `NextcloudProvider._buildNextcloudBaseUrl` to a public static
  `buildBaseUrl()`. Dialog's `_testNextcloudConnection` now imports it
  rather than duplicating the URL-building logic.
- New `OAUTH_SYNC_PROVIDERS` set in `provider.const.ts`. Re-auth button's
  hideExpression and the settings-page `requiresAuth` derivation can both
  reference it instead of hard-coding `Dropbox`.

**Simplicity**
- Settings page `syncStatus` collapses from 5 fields to 3 (providerId,
  needsAuth, isEncrypted) — empty state derives from `providerId === null`.
- Drop redundant `D_INITIAL_CFG.ADVANCED` translation key in favour of
  the existing `T.G.ADVANCED_CFG`.

**Security / logging**
- Re-auth catch path now logs `{ name: e.name }` instead of the raw error
  object — log history is exportable, no auth detail leakage.

Refs #7362

* refactor(sync): apply pass-2 review fixes — error paths, marker, factory

Cross-validated findings from the second multi-agent review:

**Correctness — keep the syncStatus stream alive on probe failure**
- Wrap the inner async block in try/catch. Previously, a rejected
  `provider.isReady()` would propagate as an observable error through
  switchMap, killing the outer subscription and freezing the status
  pill. On failure, default to `needsAuth: true` so the row stays
  meaningful.
- Replace the imperative `subscribe + .set` bridge with `toSignal()`.

**Security — finish the redaction**
- The first pass only redacted SyncLog.err; the snack `translateParams`
  still passed raw `e.message` into a `[innerHtml]` sink. Snack copy
  now uses the same `_redactErrorName(e)` helper so neither surface
  carries token/URL/stack details. Helper handles `null`/`undefined`
  thrown values explicitly.

**Architecture — structural marker decouples routing from i18n**
- Both Advanced collapsibles now carry `props.syncRole: 'advanced'`.
  The dialog routes on this stable identifier instead of the shared
  `T.G.ADVANCED_CFG` translation key (also used by Jira/Azure DevOps
  forms — a global rename would have silently broken sync).

**Simplicity — collapse 5 button factories into one**
- New `_actionBtn({ text, onClick, btnType?, hideExpression?, className? })`
  helper. Each per-action factory becomes a 3-4 line call site. ~60
  lines net reduction in the dialog component.
- Drop the orphan `props: { dropboxAuth: true }` marker on the Dropbox
  fieldGroup — its consumer (`_buildSyncFormConfig`) was deleted.

Refs #7362

* refactor(sync): apply pass-3 review fixes — auth label asymmetry, dead snack param

Pass-3 review surfaced two real findings on top of polish:

**Correctness — non-OAuth providers no longer mislabelled "needs auth"**
- The pass-2 try/catch returned `needsAuth: true` unconditionally on
  probe failure, which would surface "Authentication required" for
  WebDAV/Nextcloud/LocalFile — providers that don't have an auth
  helper. Now we capture `requiresAuth` BEFORE the throwable
  `isReady()` call and reuse it in the catch, so non-OAuth providers
  fall through to `needsAuth: false` even on transient failures.

**Simplicity — drop the dead snack translateParams**
- The `INCOMPLETE_CFG` translation key has no `{{error}}` placeholder,
  so the redacted error name was silently dropped by the translation
  pipe. Removing the param documents the actual contract: the snack
  shows static credentials-missing copy; the discriminator goes only
  to the (redacted) log.

**Polish — cleaner types, tighter helper**
- `_redactErrorName` collapses to two-arm helper: `Error.name` for
  Error instances, `'UnknownError'` for everything else. The
  null/undefined/typeof branches were exporting internal jargon to
  the user.
- The `props.syncRole` marker now uses a typed `SyncCollapsibleProps
  extends FormlyFieldProps` interface (exported from sync-form.const)
  instead of a `Record<string, unknown>` cast. Eliminates the cast at
  both write and read sites.

Refs #7362

* refactor(sync): polish round — shareReplay, subscription cleanup, doc tightening

Three deferred items from prior reviews now applied:

- shareReplay({bufferSize:1, refCount:true}) on syncSettingsForm$. The
  config-page subscribes long-term and the dialog re-subscribes per
  open; previously the no-provider branch re-fetched the
  sync-config-default-override.json asset on every fresh subscription.
  Cold-start cost is now amortised across both consumers.
- Drop the manual Subscription aggregator on ConfigPageComponent. The
  remaining cfg$ + queryParams subscriptions now use
  takeUntilDestroyed(this._destroyRef); ngOnDestroy + OnDestroy go
  away.
- Tighten dialog _isInitialSetup handling. Pass-3 review noted the
  pre-set + Object.assign pattern reads as if order matters when it
  doesn't. Move the flag into the spread payload so the intent is
  obvious at the call site, and use \!v.isEnabled directly so the
  semantics are explicit (true ⇔ first-time setup).
- JSDoc on forceOverwrite() documenting why no Material confirm is
  added — SyncWrapperService.forceUpload already gates the action with
  a native confirmDialog, and that gate also serves the 5 internal
  snackbar callers (LockPresentError / EmptyRemoteBody / JsonParse /
  LegacySyncFormatDetected / retry). Wrapping here would double-confirm.

Refs #7362

* refactor(sync): pass-4 polish — refCount:false, widen updateTmpCfg, trim docs

Cross-validated findings from the fourth review pass:

- shareReplay flips to refCount:false. Pass-4 reviewer noted that
  refCount:true only deduplicated the rare case where the dialog
  opens *while the settings page is mounted*. The far more common
  path — header-icon → dialog with no settings page open — saw the
  dialog become the sole subscriber, complete via .pipe(first()),
  and drop refCount to 0, so the next open re-fetched the JSON
  default-override anyway. With refCount:false the cached value is
  retained for the lifetime of SyncConfigService, matching the
  comment's stated intent at negligible memory cost.
- updateTmpCfg signature widens to `SyncConfig & { _isInitialSetup?:
  boolean }`. Drops the call-site cast (a code smell that pretended
  the type was wider than it was) and documents that _isInitialSetup
  is a real, expected payload field.
- Trim the misleading comment around `_isInitialSetup: \!v.isEnabled`.
  The "Spread last so Object.assign honours this" line wasn't true —
  it's an object literal property, not a spread. New comment states
  the actual semantics: first-time setup ⇔ sync was previously
  disabled.
- Trim forceOverwrite() JSDoc from 6 lines to 2 — same content,
  matches the project's preference for terse method comments.

Refs #7362
2026-04-25 22:39:22 +02:00
..
constants test(e2e): fix done-toggle selector to use element instead of class 2026-03-24 16:25:42 +01:00
fixtures Feat/to me it looks like there are lots of 60dd04 (#7280) 2026-04-20 12:04:38 +02:00
helpers test(e2e): use correct route /#/tag/TODAY/tasks instead of /#/tag/TODAY 2026-03-15 18:48:00 +01:00
pages Feat/issue 7362 9d46d3 (#7363) 2026-04-25 22:39:22 +02:00
tests fix(sync): break iOS WebDAV conflict-dialog loop (#7339) 2026-04-25 22:36:14 +02:00
utils test(e2e): silence ERR_FAILED noise from intentional JS aborts 2026-04-24 17:40:28 +02:00
.gitignore fix(gitignore): correct screenshots directory path in .gitignore 2026-01-21 21:05:29 +01:00
CLAUDE.md build: update CLAUDE.md 2026-01-04 14:52:35 +01:00
global-setup.ts Feat/to me it looks like there are lots of 60dd04 (#7280) 2026-04-20 12:04:38 +02:00
playwright.config.ts test(e2e): increase webServer startup timeout to 2 minutes 2026-03-18 13:14:10 +01:00
README.md feat(e2e): streamline e2e test development with improved infrastructure 2026-01-03 11:21:40 +01: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
│   ├── schedule.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)