# Ky end-to-end tests

Ky (`dceky`) is the team's TypeScript wrapper around Cypress: shared structure, profiles,
globals, credentials handling, and custom commands. Test code calls `ky.` instead of `cy.`
(`global.ky = global.cy` in the generated `cypress/support/e2e.ts`). Each app has (or should
have) its own test repo; `immersive-classroom-tests` is the model. Katalon, Kaixa and Raixa
are retired.

## Layout (as in `immersive-classroom-tests`)

```
cypress/
  e2e/<Folder>/<name>.ky.ts          # tests; the .ky.ts suffix is required; folders group features
  e2e/<name>.ky.ts                   # top-level tests are fine too
  commands/<name>.ts                 # one custom command per file (ky.<name>()); index.ts is generated
  globals/GlobalValues.ts            # plain values; `dependsOn: 'baseURL'` maps per-environment values
  globals/GlobalResources.ts         # video ids, links, fixtures
  globals/GlobalCredentials.ts       # secrets; gitignored; never read or paste it
  profiles/Default.Profile.ts        # non-URL defaults (courseId, playerName...)
  profiles/<Env>.Profile.ts          # one per environment, each with a baseURL (Stage, Prod, EdtechTeam...)
  support/e2e.ts, support/kyCommandDeclarations.ts   # generated by dceky
cypress.config.ts                    # generated: `genConfiguration()` from dceky
cypress-results/<timestamp>/<Profile>-<browser>/     # headless output (gitignored); index.html + all-runs.html
tsconfig.json                        # rootDir ./cypress, target es6, types node
package.json                         # devDeps: cypress, dceky, playwright-webkit, mochawesome*, cypress-parallel...
```

`package.json` scripts delegate to dceky: `"ky:setup": "npm explore dceky -- npm run ky:setup"`,
`"ky:start": ...ky:start`, `"ky:dev": ...ky:dev`, plus `"ky:headless-helper": "cypress run --quiet"`.

A custom command file:

```ts
/// <reference types="cypress" />

declare global {
  namespace Cypress {
    interface Chainable {
      /**
       * What it does
       * @author Your Name
       * @param opts ...
       */
      myCommand(opts: { user: string }): Chainable<void>;
    }
  }
}

const myCommand = () => {
  Cypress.Commands.add('myCommand', (opts: { user: string }) => {
    // ...uses ky.getProfileValue('courseId'), ky.visit(), ky.waitForElementVisible('#Player-container')...
  });
};

export default myCommand;
```

A test: `describe` / `it`, with `ky.setUp()` first (IC's creates a clean test event through
admin API calls and yields its `ihid`), `ky.launchICAs({ user: 'student' })` to launch as a
profile user, assertions on the team's `Component-element` class names, and `ky.tearDown()`
last. Built-in helpers seen in the model: `ky.uniquify`, `ky.typeInto`,
`ky.waitForElementVisible`, `ky.extractDataFromClass[ByContents]`, `ky.genTextOfLength`,
`ky.getProfileValue`, `ky.clearAllCookies`, `ky.logIntoPorta`, `ky.launchAs`, `ky.reload`.
IC exposes `/landing-page-for-automated-testing` and a self-launch route
(`/canvas/launch/self?courseId=...&selfLaunchState=...`) for this; test instances need
`CLEANUP_ALLOWED=true` and `TEST_COURSE_IDS` so the setup's force-clean calls are allowed.

## Running

| Command | Use |
| --- | --- |
| `npm run ky:dev` | developers: re-runs setup, then the chooser |
| `npm run ky:start` | QA and CI: no files touched; prompts, or env vars |
| `npm run ky:report` | opens the HTML report of the last headless run |
| `npm run ky:setup` | regenerate Ky files after updating dceky or adding commands |

Non-interactive headless run against a deployed instance (the verification step):

```bash
HEADLESS=true BROWSER=chrome,webkit PROFILE=<Env> E2E_TEST_FOLDER=all THREADS_PER_COMBO=2 NUM_COMBOS_IN_PARALLEL=1 npm run ky:start
npm run ky:report     # or open cypress-results/<timestamp>/index.html
```

`PROFILE` names the profile whose `baseURL` is the instance the developer deployed to; add
one if missing (`<Env>.Profile.ts` with `baseURL` only). Ky needs Node 20+. WebKit needs
`playwright-webkit` and the experimental flag; its driver is incomplete (`cy.origin()`
unsupported, `cy.type()` differences), so a WebKit-only failure deserves a second look before
it blocks a release. Record the pass/fail counts and the results folder in the
SecurityUpdates entry.

## What to write for a security PR

Tests prove the upgraded app still works where users touch it. Minimum: the LTI launch
succeeds and the landing page renders its main controls. Then one test per user flow that
touches a package you bumped by a major version or removed (if `query-string` went, every
screen that parses URL parameters; if `axios` moved to 1.x inside a lib, the flows that call
Zoom or Canvas through it). Follow the existing tests' structure and the team's code rules:
TypeScript, JSDoc on every function, single quotes, arrow functions, trailing commas, `===`,
no nested ternaries. Run locally first (`npm run ky:dev`, Stage or a team instance), then
headless on the deployed instance.

## When an app has no Ky repo yet

Scaffold `<app>-tests` from the model repo and the dceky README:

1. Create the repo under harvard-edtech, clone, `npm init -y`.
2. `npm i --save-dev cypress dceky typescript playwright-webkit`, then `npx cypress open` once
   (E2E → Continue → close at the browser chooser), then add the `ky:*` scripts above and run
   `npm run ky:setup`. Commit the generated files.
3. Copy the *structure* from `immersive-classroom-tests`: `profiles/` (this app's baseURLs),
   the three `globals/` files (this app's values; `GlobalCredentials.ts` stays gitignored and
   empty in git), `tsconfig.json`, `.gitignore`, README. Port only the custom commands that
   make sense here (a launch command for this app, setUp/tearDown if it has admin test
   endpoints); do not copy IC's tests.
4. Write the first tests (launch + landing page), run `npm run ky:dev` locally, open a PR.

Ask Gabe which instance each profile should point at and where credentials are kept before
inventing either.
