Use when user asks to write, create, run, or debug Playwright e2e tests in the Gramax project. Triggers on keywords like e2e, playwright, test, spec, QA.
---
name: e2e
description: Use when user asks to write, create, run, or debug Playwright e2e tests in the Gramax project. Triggers on keywords like e2e, playwright, test, spec, QA.
---
# Writing E2E Tests
Framework: Playwright + custom fixtures/POMs. All tests in `e2e-pw/`.
## Workflow
The user is often a QA tester who describes tests in human language; you translate intent into code and decide the technical details (fixtures, POMs, locators). Similar specs live in `e2e-pw/platforms/<platform>/tests/`, POMs in `e2e-pw/platforms/<platform>/pom/` and `e2e-pw/shared-pom/`; read the app's UI components for elements, roles and text.
When the request leaves behavior open — platform, scope, expected result, which UI path, locale — ask in one message as a numbered list the user can answer by number; ask about behavior and expectations, never about implementation. Skip the questions when the request already gives steps and expected results.
For a new test described in human language, show the plan in this shape and write the spec once the user confirms it:
```
Test: <name>
Platform: web / docportal
Fixture: editorTest / homeTest / catalogTest / baseTest
Test data: <files/catalogs to create>
Steps:
1. <action>
2. <action>
Assertions:
- <assertion 1>
- <assertion 2>
```
Running, debugging or fixing existing specs, and headless runs, go straight to the work.
## Fixture Selection
```
Editor content/formatting → editorTest
Home page / catalog list → homeTest
Navigation inside a catalog → catalogTest
Custom setup (web) → baseTest
Docportal → baseTest (docportal)
```
### Hierarchy (web)
```
baseTest — web context, files, localStorage
├─ homeTest — + homePage (HomePage)
├─ catalogTest — + catalogPage (CatalogPage)
│ └─ editorTest — + editor (ArticleEditorPom)
└─ (direct use for custom setups)
```
### Hierarchy (docportal)
```
baseTest — web context, API login/source setup
```
## Running Tests
```bash
cd e2e-pw
# Build & start: web (6001; in a worktree GX_E2E_WEB_PORT) / docportal (6004)
bun run web:build && bun run web:start
bun run docportal:build-git && bun run docportal:build && bun run docportal:start
# Run
bunx playwright test --project=web # all web
bunx playwright test --project=web basic.spec.ts # single file
bunx playwright test --project=web -g "test name" # by name
bun run ui # interactive UI
bunx playwright test --project=docportal-prepare --project=docportal
```
Projects: `web`, `web-stash` (`web:ci` runs both), `web-stash-timings`, `web-enterprise`, `static` (6002), `docportal-prepare` → `docportal` (6004), `docportal-enterprise` (the new DocPortal on the GES stand, specs in `platforms/docportal/tests/enterprise`; each spec starts its own portal, so no port). `docportal` runs the specs from `platforms/docportal/`. `docportal-enterprise` runs in the CI job `docportal-enterprise-e2e-pw`, and locally through the stand: `GES_E2E_PROJECT=docportal-enterprise ./scripts/enterprise-e2e.sh platforms/docportal/tests/enterprise`.
## Platforms
| Platform | Port | State | Setup |
|----------|------|-------|-------|
| web | 6001 | Reset each test (isolated) | `files` fixture via DOM |
| docportal | 6004 | Persistent | API setup, `docportal-prepare` |
| static | 6002 | Static build | Pre-built |
## Locators
**Only `getByRole` and `getByText`.** `getByPlaceholder` and `getByLabel` are fine where they read
naturally — they resolve through accessible names too. `getByTestId` is a last resort. CSS and
XPath selectors — `locator(".foo")`, `locator("[data-qa=…]")`, class names, tag chains, `:nth-child`
— are **not allowed**, and neither is reaching for a `data-*` attribute as a hook.
When an element has no usable role or accessible name, the answer is to **fix the component**, not
to work around it in the test. Give the button a real `<button>`, an `aria-label`, a visible text —
whatever the element is actually missing. A test that reaches into markup is a test that breaks on
the next restyle, and it hides an accessibility gap in the product.
Editing app code to make an element addressable is expected and welcome. It is not scope creep.
```typescript
// GOOD — the element says what it is
page.getByRole("button", { name: "Save" }).click();
page.getByRole("menuitemradio", { name: "master" }).click();
page.getByText("Article Title").click();
// LAST RESORT — only when the element genuinely cannot carry a role or a name
page.getByTestId("add-catalog").click();
// NOT ALLOWED — fix the component instead
page.locator(".btn-primary > span").click();
page.locator(".right-extensions i").first().click();
page.locator("[data-qa='qa-publish-tab']").click();
```
If you find yourself writing a comment that explains which CSS class the app happens to render, stop:
that is the moment to add the role or the label to the component.
biome checks this: `.biome/plugins/no-css-locator.grit` flags every `.locator(…)` in `e2e-pw/**`.
`lint:ref` judges a touched file whole, so a file you edit leaves with no `.locator(…)` in it — the
CSS locators already there get rewritten too. A locator that cannot be replaced (markup of a third-party
package with no roles) stays with `// biome-ignore lint/plugin: <why>` on the line above.
### Fixing the component: use the real element, not an ARIA patch
Making an element addressable means giving it the **right tag**, not decorating the wrong one.
```tsx
// GOOD
<button type="button" aria-label={t("git.branch.actions")} onClick={…}>
// BAD — a div wearing a button costume
<div role="button" tabIndex={0} aria-label={…} onClick={…}>
```
`role="button"` plus `tabIndex={0}` on a `<div>` or `<span>` reproduces by hand what `<button>` gives
for free — keyboard activation, focus order, Enter/Space handling — and it always reproduces some of
it wrong. Use `<button type="button">`; `type` is required, or the button submits any form it lands in.
**Never silence an a11y lint.** `biome-ignore lint/a11y/*` is not an accepted way out: that rule
firing *is* the review telling you the element is wrong. If a semantic element genuinely does not
fit — an existing click target would nest, a styled wrapper would break — change the surrounding
markup so it does, or say plainly in the MR why it cannot be done. Do not commit the suppression.
Suppressions in general are a smell here. The only one currently accepted in `e2e-pw` is
`lint/correctness/noEmptyPattern` on fixture signatures, because Playwright *requires* the
`async ({}, use)` form to detect fixture dependencies and biome has no way to know that.
## Snapshots
- Appearance is checked with `expect(locator).toHaveScreenshot("<name>.png")` on the element, not the
page. Geometry and computed styles are read only to drive an action (a drag, a click point), never to
compare with a number.
- Before a shot: `page.mouse.move(0, 0)` and `dropFocus(page)` from `@utils/snapshot`; an element taller
than its scroll container goes through `inTallWindow`. Keep anything run-specific out of the frame — the
catalog name in the navigation carries the run id.
- Page chrome no shot is about (editor toolbar, diff navigator, corner buttons, template picker,
prev/next links) is hidden for every shot by `e2e-pw/utils/snapshot.css`. New chrome that shows up in a
frame goes there, not into a `mask` in the spec.
- Several shots in one test go through `expect.soft`, so one differing frame does not hide the rest.
- A local run does not compare snapshots (`ignoreSnapshots: !isCI`), so a green local run says nothing
about one. A new snapshot without a baseline fails in CI.
- Baselines are taken in the CI image: `bun run --cwd e2e-pw web:snapshots -- <spec>` (Docker; on Apple
silicon with Rosetta). A spec that needs GitLab cannot run there: its baseline is the `*-actual.png` the
MR pipeline leaves in the `web-e2e-pw` artifact. Look at every new frame before committing it next to the
spec, in `<spec>.ts-snapshots/`.
- Baselines live in Git LFS (`e2e-pw/.gitattributes`). Without git-lfs a checkout holds pointer files and
`git add` commits a new picture as a plain blob.
## Test Examples
**Editor:**
```typescript
import { editorTest } from "@web/fixtures/editor.fixture";
editorTest("does something", async ({ editor }) => {
await editor.setMarkdown("Hello(*)");
await editor.press("ControlOrMeta+B");
await editor.type("bold");
await editor.assertMarkdownContains("**bold**");
});
```
**Home/catalog:**
```typescript
import { homeTest } from "@web/fixtures/home.fixture";
homeTest.use({ files: { "my-catalog": { "article.md": "# Hello", "doc-root.yml": "title: My Catalog\n" } } });
homeTest("shows catalog", async ({ homePage }) => {
await homePage.workspace.assertHasCatalogs(["my-catalog"]);
});
```
**Docportal:**
```typescript
import { baseTest as test } from "@docportal/fixtures/base.fixture";
test.use({ source: "env", user: "env" });
test("navigates", async ({ basePage }) => {
const page = basePage.raw;
const item = page.getByRole("button", { name: "Catalog" });
await item.click();
// assert what the click produced, never a generic "page loaded" barrier
await expect(page.getByRole("heading", { name: "Catalog" })).toBeVisible();
});
```
## Fixtures
### Test data setup
**`files`** — inline file tree (primary method):
```typescript
homeTest.use({ files: { "catalog": { "art.md": "# Title", "doc-root.yml": "title: Cat\n" } } });
```
Keys = dirs/files, strings = content, objects = subdirs, `number[]` = binary.
**`dir`** — load from filesystem: `catalogTest.use({ dir: new URL("./test-catalog", import.meta.url) });`
**`zip`** — upload and extract ZIP file.
### Options (web)
`files`, `zip`, `dir`, `source` (`"env"` | SourceData), `isolated` (true), `isReadOnly` (false), `experimentalFeatures` (string[]), `startUrl` ("/").
Editor extras: `initMd` (string), `firstEnter` (true).
### Options (docportal)
`source`, `user` (`"env"` | AuthCredentials), `isolated` (true), `startUrl` ("/").
### Serial mode
`test.describe.configure({ mode: "serial" })` — when tests depend on each other.
### Step grouping
`await test.step("label", async () => { ... })` — for better reporting.
## POMs
**BaseSharedPage** (`shared-pom/page.ts`): `goto(path)`, `waitForUrl(url)`, `assertUrl(url)`, `assertNoModal()`, `navigate(path)` (pushState), `copyFileToClipboard(path)`, `raw` (Page), `modal` (Locator). `waitForLoad()` exists but is internal to `goto` — a spec calling it is almost always compensating for a missing assertion.
**HomePage** (`web/pom/home.page.ts`): `topBar` (TopMenu: `getAddCatalog()`, `getSwitchWorkspace()`, `getSwitchUiLanguage()`, `getSwitchTheme()`), `workspace` (WorkspacePom).
**CatalogPage** (`web/pom/catalog.page.ts`): `currentArticleContent(markdownOnly?)`, `readFile(path)`, `getCatalogActions()`, `getArticleProperties()`, `getNavTreeState(catalogName)`.
**ArticleEditorPom** (`web/pom/editor.pom.ts`): `setMarkdown(md, opts?)`, `markdown()`, `type(text)`, `press(keys)`, `focus()`, `pasteHtml(html)`, `pasteText(text)`, `forceSave()`, `clickToolbar(button)`, `hoverToolbar(button)`, `assertMarkdown(expected, opts?)`, `assertMarkdownContains(expected)`, `assertMarkdownValid()`, `bottom()`.
**WorkspacePom**: `assertHasCatalogs(names[])`, `assertCurrentWorkspace(config)`, `assertWorkspaces(configs[])`.
**CatalogPom** (`web/pom/catalog.pom.ts`): `props()`.
**Theme** (`shared-pom/theme.ts`): `assertHasTheme(theme)`, `assertThemeChanged()`, `switch(locator?)`.
### Atoms (shared-pom/atoms/)
**Dropdown**: `open()`, `close()`, `isOpen()`, `getItems()`, `findItemByTitle(title)`, `assertHasItem(item)`, `assertHasItems(items[])`, `assertTriggerVisible()`, `assertContentVisible()`, `assertContentHidden()`.
**DropdownItem**: `click()`, `hover()`, `assertVisible()`, `assertHidden()`. Props: `title`, `description`, `hasSubContent`.
**Button**: `click()`, `hover()`, `text()`, `assertVisible()`, `assertHasText(text)`.
**Select** (extends Dropdown): uses `select-content`/`select-item` test IDs.
## Editor Specifics
`(*)` in `setMarkdown` = cursor position. Keys: space-separated, modifiers with `+` (`ControlOrMeta+B`).
Toolbar buttons: `bold`, `italic`, `strikethrough`, `heading-2/3/4`, `bullet-list`, `ordered-list`, `task-list`, `code`, `table`, `note`, `diagrams`, `pencil-ruler`.
`md` template tag (`@utils/utils`) removes indentation from template literals.
## Naming
`describe` and `test` titles read like a spec: the `describe` is a chapter, each `test` is a clause of that chapter. English, present-tense statements of fact — no "should", "must", "can", "correctly".
```typescript
// GOOD — spec chapter + clauses
describe("OpenAPI content block", () => {
test("renders spec as code block after insert", ...);
test("updates TOC after spec edit", ...);
});
// BAD
describe("openapi tests", () => {
test("should render the spec correctly", ...);
});
```
Assertion messages follow the same rule: state the expected fact (`"toolbar sticks to viewport top"`), not an obligation (`"toolbar should stick..."`).
## Conventions
1. One behavior per test
2. Use POMs, not raw locators
3. `getByRole`/`getByText` only — no CSS, no XPath, no `data-*` hooks. Missing role or name means the
component gets fixed; `getByTestId` is the last resort, not the default
4. `goto()` already ends with a ready app — don't add a barrier after navigation; assert the thing the navigation produced
5. `serial` only when order matters
6. `files` fixture for test data, not manual setup
7. Files: `<feature>.spec.ts`, group in `describe` blocks
8. **Do not modify test infrastructure (fixtures, POMs, utils, config) without asking.** Only `*.spec.ts` files can be created/edited freely.
9. For examining playwright's trace files use playwright skill
## Verification & Invariants
1. A spec that never ran is a hypothesis, not a test. Can't run it in this env → stop and say so; don't commit it.
2. One green run proves nothing about flakiness. Every written or rewritten test runs repeatedly under parallel load before it is done: `bunx playwright test --project=web <file> -g "<name>" --repeat-each=10 --retries=0` (default 4 workers). CI retries twice, so a flaky test passes there and rots the suite. Any failure out of N → find the race and fix it, don't raise timeouts or add sleeps; then repeat the full N again. Report the pass count (`10/10`) when handing the test over.
3. Timing/traffic mechanics (debounce, dedupe, caching) → assert request counts (`page.route` counter: type N chars → expect ≤2 POSTs). Final state can't prove frequency.
4. Any acquire/release mechanism (hold/lock/counter): per acquire, answer "who releases on error / unmount / duplicate event?" and write one negative-path test (route intercept forces the error).
5. Wait on what the user can see, never on an internal flag. The app exposes readiness through the UI itself — the unsaved dot (`data-testid="save-status"`, `data-state="saving|saved"`), the sync spinner, the active nav item, the absence of a loader. There is no `data-app-busy` attribute and no `idle()` barrier; both were removed because a test that waits on an invisible flag proves nothing about the product.
6. Leak detection lives in the fixtures, not in the tests: the `busyInvariant` auto-fixture waits after every web test until every AppBusy hold is released, and names the kind when one is not (`AppBusy holds left after the test: ["save"]`). An armed debounce is not a leak — it releases itself, which is why the check waits (`BUSY_DRAIN`) instead of failing on the spot. A forgotten `release()` now costs the user directly: a stuck `save` hold leaves the unsaved dot lit forever. AppBusy itself carries no watchdog timers or thresholds; don't add production-side alarms.
7. A readiness assertion that fails must fail the test — never try/catch-and-log. Swallowing it into `console.error` means the test walks on and dies later somewhere else, which is exactly the diagnostic loss a blind `sleep` caused.
8. App timings live in `core/ui-logic/timings.ts` (localStorage `gx-timing-<key>` overrides). There is **no** e2e profile — the defaults are what the suite runs on. A test that targets a timing window sets the value itself and reloads (`autosave.spec.ts` widens `saveDebounceMs` 500 → 3000, because under four workers a locator resolution eats the window and the window is the subject).
9. Cumulative per-kind hold counters are available via `window.appBusy().created` for tests that assert frequency ("20 keystrokes arm the debounce a handful of times, not once per key"). That snapshot is diagnostics, not a readiness signal — never wait on it.