# Testing Guide

## High-Level Cypress Testing Concepts

### 1. **Dual Codebase Requirement**
Tests require **two repositories working together**:
- **Frontend** (`glib-web-npm`): Contains the Cypress tests
- **Backend** (`glib-web`): Must have corresponding test pages in `/app/views/json_ui/garage/test_page/`

The tests hit `/glib/json_ui_garage?path=test_page/{name}` on a backend that
mounts the garage engine and runs the LOCAL gem + npm pair. The canonical
backend is the gem's dummy-app (`glib-web/test/dummy-app`) -- fully
project-agnostic, links this package, and auto-builds it via vite-ruby:

```
cd ../glib-web/test/dummy-app && bin/rails s -p 3230
yarn cypress run    # localhost:3230 is the default backend
```

**Run locally in one command.** `scripts/cypress-local.sh` does the two steps
above (boot the dummy-app, wait for it, run Cypress, tear it down) as a single
command. It assumes `glib-web` is a sibling checkout; if not, set
`GLIB_WEB_DIR`. If a server is already on the port it reuses it instead of
booting one.

```
yarn test:local:setup   # first run only: bundle/yarn install + db:prepare
yarn test:local         # boot backend + run full e2e suite + tear down
yarn test:local:open    # same, interactive Cypress UI
yarn test:local --spec cypress/e2e/glib-web/form.cy.js   # a single spec
GLIB_WEB_DIR=/path/to/glib-web BACKEND_PORT=3230 yarn test:local   # overrides
```

A consumer host app also works via `--expose BACKEND_HOST=...,BACKEND_PORT=...`.
Specs build URLs via `testPageUrl(name)` (or `garageUrl(path, params)` for
garage pages outside `test_page/`) from `cypress/helper.js` — never hardcode a
host. Setup for both backends (and host-app caveats: bundle rebuilds after
npm edits, disabling rate limiting for batch runs) is documented in
[CONTRIBUTING.md](../CONTRIBUTING.md) under "Running Cypress: the gem's
dummy-app is the backend".

### 2. **Integration Testing Philosophy**
Tests are **full-stack integration tests**, not unit tests:
- No mocking/stubbing of glib API requests — the backend must be running and tests verify the entire request-response cycle
- Stubbing external third-party services (e.g., reCAPTCHA) is acceptable since they cannot run in a test environment
- Form submissions are verified by backend rendering the data back

This is fundamentally different from typical frontend testing (Jest/Vitest with mocks).

### 3. **Test Page as Contract**
Each Cypress test has a **matching backend test page** (jbuilder file):
- `form.cy.js` → `test_page/form.json.jbuilder`
- `dialog.cy.js` → `test_page/dialog.json.jbuilder`

The test page acts as the **contract** between frontend and backend tests.

### 4. **JSON-Driven UI Architecture**
The framework uses **server-rendered JSON instructions**:
- Backend sends JSON describing what components to render
- Frontend interprets and renders Vue components
- Actions (button clicks) send JSON back to server
- Server responds with new JSON to update UI

Tests verify this **declarative UI pattern** works correctly.

### 5. **Test Page Pattern as Documentation**
The `doc/garage/` examples you mentioned serve dual purpose:
- **Development examples** - Show how to use components
- **Test fixtures** - Provide data for Cypress tests

The tests essentially **validate the examples work as documented**.

### 6. **Backend-First Test Development**
To add a new test, you must:
1. Create backend test page first (in `glib-web/app/views/json_ui/garage/test_page/`)
2. Implement the feature using JSON UI
3. Write Cypress test that exercises it

You **cannot write frontend tests in isolation**.

---

These 7 concepts explain **why the test structure exists** and **what you need to get started**. Everything else (selectors, assertions, etc.) is standard Cypress mechanics.

### 7. **Do Not Run `bin/vite dev` Separately During Cypress Tests**
Running the Vite dev server separately (`bin/vite dev`) while running Cypress tests causes blank pages (Vue app fails to mount). Just use the Rails server alone — it handles Vite compilation internally.

### 8. **Sandboxed Agent Environments: Invoke Cypress Explicitly**

In sandboxed AI-agent shells, `yarn test` (and other Cypress invocations
whose command text doesn't match the environment's sandbox allowlist) can
crash with SIGSEGV before Cypress even prints its banner — the browser
cannot start inside the sandbox. The reliable invocation shape is explicit:

```
yarn cypress run --browser chrome --spec <comma-separated .cy.js files> \
  --expose BACKEND_HOST=localhost,BACKEND_PORT=3230
```

If a run segfaults instantly with no spec output, suspect the invocation
shape (or a sandboxed launch), not the tests.

### 9. **Coverage Threshold Gate**

`yarn test:coverage` ends with `yarn test:coverage:check` (`nyc
check-coverage`), which EXITS NON-ZERO if any metric drops below the
thresholds pinned in `package.json`. The thresholds sit a couple of points
under the actual level at the time they were set — they are a regression
floor, not a target. When coverage rises meaningfully, ratchet them up;
never lower them to make a failing check pass without discussing why.

## Cypress Coverage Workflow

- **How it works**: coverage (the JS analog of simplecov) is collected by
  `@cypress/code-coverage` from an istanbul-instrumented bundle and reported
  by `nyc` (`.nycrc.json` holds the include list and thresholds). The
  instrumentation ships in `plugins/viteDefaultConfig.js` (env-gated
  `vite-plugin-istanbul` with `forceBuildInstrument`, since served bundles
  are builds), which the gem's dummy-app uses as its whole vite config --
  inert unless the build runs with `VITE_COVERAGE=true`.
- **Step-by-step run** (against the gem's dummy-app):
  1. From `glib-web/test/dummy-app`:
     `VITE_COVERAGE=true bin/vite build --force`, then start the server with
     `VITE_COVERAGE=true bin/rails s -p 3230` (the env var keeps autoBuild
     from rebuilding uninstrumented).
  2. From this repo: `yarn clean:coverage`, then
     `yarn cypress run --expose BACKEND_PORT=3230` (the e2e support file
     collects `window.__coverage__` automatically).
  3. From this repo: `yarn nyc report`.
  4. Afterwards, rebuild WITHOUT `VITE_COVERAGE` (`bin/vite build --force`)
     so the dummy-app goes back to serving uninstrumented code.
- **Where to read results**: HTML report at `coverage/index.html`; summary printed in the terminal; raw data in `.nyc_output` and `coverage/coverage-final.json`.
- Baseline for reference: 2026-07-19, full e2e suite (257 tests) -- lines
  74.3%, statements 72.9%, functions 72.4%, branches 63.9%.
