How tests work in the Prosjektportalen 365 monorepo and how to write, run and fix them. Use when asked to "add a test", "write a component test", "unit test", "run the tests", "heft test", "jest", "coverage", "why does the test fail", "mock the data adapter", "playwright", "e2e", "smoke test", "flaky test", "test the web part", "integration test", "test against the tenant", "test the data service". Encodes the shared Jest harness (pp365-jest-config), the PnPjs stub, string module resolution, ...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Pp365 Testing?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/puzzlepart-pp365-testing)
---
name: pp365-testing
description: How tests work in the Prosjektportalen 365 monorepo and how to write, run and fix them. Use when asked to "add a test", "write a component test", "unit test", "run the tests", "heft test", "jest", "coverage", "why does the test fail", "mock the data adapter", "playwright", "e2e", "smoke test", "flaky test", "test the web part", "integration test", "test against the tenant", "test the data service". Encodes the shared Jest harness (pp365-jest-config), the PnPjs stub, string module resolution, the coverage floors, the integration tests of the data layer (node --test against the tenant) and the Playwright suite (smoke, flows, local). Pair with the playwright-cli skill for browser work.
---
# Testing in PP365
Authoritative description (Norwegian): `.development-guide/spfx/testing.md`. This skill is the operational summary for agents.
## Layers and where they run
| Layer | Location | Runs |
|---|---|---|
| Unit + component tests | `SharePointFramework/<Solution>/src/**/*.test.ts(x)` | `heft test`, inside `npm run build`, `npm test`, `rush build`/`rebuild` and CI. A failing test fails the build. Not in `build:<channel>`, `postversion` (`heft build`) or `heft start`. Output: `jest-output/JUnit.xml`, `jest-output/coverage/`. |
| Runtime contract tests | `SharePointFramework/shared-library/test/runtime/*.test.mjs` (`node --test`: real PnPjs 4, a fake transport, SPFx's relative URLs via `pre.prepend`) | `npm run test:runtime`, part of shared-library's `build` and `test` after `heft test`. Add one whenever code composes PnPjs queryables: Jest stand-ins missed `getTermStore` throwing under SPFx. |
| Release checks | `Install/Build-Release.ps1` | Every release build, so CI: no missed coverage floor (grepped from `rush-logs`); a fresh `.sppkg` per selected solution; no `pp365-*` external in a `dist` AMD `define([...])` header; no hashed third-party class name (`react-calendar-timeline_<hash>`, `rct-*`, `ms-Fabric`, `ms-Grid-*`) in `dist/*.js`. |
| Integration tests | `integration/` (Rush project `pp365-integration`, `node --test` on `tests/**/*.test.ts`, type stripping) | Job "Integration tests (test channel)" in `ci-channel-test.yml`, beside E2E after either upgrade path. `[skip-integration]` skips it. Never in `rush build` (it needs a tenant). |
| E2E | `e2e/` (Rush project `pp365-e2e`, Playwright) | Job "End-to-end smoke (test channel)" in `ci-channel-test.yml`, after the test-channel upgrade, full or packages-only (`[apps-only]`), running `tests/smoke` and `tests/flows`. `[skip-e2e]` skips it. |
## Running
- One solution: `cd SharePointFramework/<Solution> && npm test` (= `heft test`, builds first; shared-library adds `test:runtime`). One file: `npx heft test --test-path-pattern <name>` (a regex over the compiled test file's path, e.g. `ProjectStatus/reducer`). It works from SPFx 1.24 (`@rushstack/heft-jest-plugin` 2.0.19 passes it as Jest 30's `testPathPatterns`); under 1.23 (2.0.6) it went out under the Jest 29 name, which Jest 30 ignores, and every file ran.
- Consumers need the shared library built first: `rush rebuild -o pp365-shared-library` from the root.
- Integration locally: `cd integration && cp .env.example .env`, the e2e user's session from `npx playwright test --project=setup` in `e2e/` (about two days), the library built, then `npm test` (seconds). Details below.
- E2E locally: `cd e2e && cp .env.example .env` (fill in) `&& npx playwright install chromium && npm test`. `npm run test:ui` opens Playwright's UI mode; the Inspector is `--debug` or `PWDEBUG=1`.
## Coverage floors
Each solution's `config/jest.config.json` sets `coverageThreshold.global` (statements, branches, functions, lines), floors measured in phase 4. Raise them when coverage grows; never lower them. Jest reports a miss but Heft's test phase passes, so deleting tests or adding untested code stays green locally and fails `Build-Release.ps1` (CI). Read Jest's coverage summary before pushing. Coverage counts only the files the tests load: a new test that imports a large untested module (ProgramWebParts' `SPDataAdapter.ts`, 34 methods) pulls all of it in and can drop a floor (functions fell from 63 % to 44 % on 2026-10-08). Test the logic in a module of its own with its dependencies passed in (`ProgramWebParts/src/data/childProjectRemoval.ts`), or cover the module fully. The fast loop (`heft run --only test`) prints no threshold: read `jest-output/coverage/coverage-summary.json` (`total`) after a full run of the solution's suite.
## The harness: `pp365-jest-config` (SharePointFramework/.jest-config)
Each `config/jest.config.json` extends `pp365-jest-config/jest-shared.config.json`, which extends the rig's (jsdom, `lib-commonjs` roots, coverage, JUnit) and adds:
- `lib/setup.js`: jest-dom matchers; polyfills `matchMedia`, `ResizeObserver`, `IntersectionObserver`, `scrollTo`; `window.__themeState__` with SharePoint's default palette; `dir="ltr"` on `<html>`.
- `lib/resolver.js`: resolves SPFx string modules (`SharedLibraryStrings`, `SharedResources`, `<Solution>Strings`) via `config/config.json` `localizedResources` to the `nb-no` bundle (`PP365_TEST_LOCALE=en-us` switches). `lib/amdTransform.js` turns those AMD bundles into CommonJS. A syntax error in a loc `.js` therefore fails the test run.
- `lib/spfxStub.js` mapped over `@microsoft/sp-*` (their lib-commonjs needs Microsoft-internal modules): chainable proxy plus real values (`KNOWN`): `DisplayMode`, `Guid`, `Log`, `Text`, `Version`, `Environment(Type)`, `SPHttpClient`/`HttpClient`, `UrlQueryParameterCollection`, `PropertyPaneFieldType`, `PlaceholderName`, `Dialog.alert`/`prompt`, the `PropertyPaneTextField`/`Toggle`/`Dropdown` factories (returning `{ type, targetProperty, properties }`), and small real base classes (`BaseApplicationCustomizer`, `BaseListViewCommandSet`, `BaseFieldCustomizer`, `BaseClientSideWebPart`, `BaseDialog`); extend `KNOWN` when a test needs more. `@microsoft/sp-lodash-subset` maps to real lodash. `react-markdown` renders its source as text; `rehype-*`/`remark-*` are no-op plugins.
- `lib/pnpStub.js` mapped over `@pnp/*`: PnPjs 4 is ESM-only and cannot be required under Jest. Imports and chaining succeed; awaiting a PnP call rejects with "PnPjs is not available in unit tests". Mock the adapter/service instead. The pure `@pnp/core` helpers (`stringIsNullOrEmpty`, `dateAdd`, `getHashCode`, `getGUID`, `combine`, `isArray`, `isUrlAbsolute`, an in-memory `PnPClientStorage`) are real.
- `moduleNameMapper`: `pp365-shared-library`, `pp365-projectwebparts`, `pp365-portfoliowebparts` resolve to their `lib-commonjs/` output, by the bare name, by `<package>/lib` and by `<package>/lib/<path>`. A specifier the mapper misses reaches the ES module build in `lib`, and the test file fails to load with `SyntaxError: Unexpected token 'export'` before any test runs; `pp365-shared-library/lib` itself was missed until 2026-10-26. `moduleDirectories: ["node_modules", "lib-commonjs"]` resolves the consumers' bare `baseUrl` imports (`'data'`, `'models'`, `'components/X'`).
- jest-dom types come from `src/jest-dom.d.ts` in each solution (the rig pins `typeRoots`, so `compilerOptions.types` cannot list the package).
- `lib/axe.js` (with `lib/axe.d.ts`): `import { axeComponent } from 'pp365-jest-config/lib/axe'`, then `expect(await axeComponent(container)).toHaveNoViolations()`, axe-core through jest-axe with the WCAG 2.1 A and AA and 2.2 AA rules, `color-contrast` off. Requiring it registers the matcher, so only tests that use it load axe-core. When and how: pp365-a11y.
- `lib/announce.js` (with `lib/announce.d.ts`): `import { announced } from 'pp365-jest-config/lib/announce'` returns the newest message in each live region on the page, for `await waitFor(() => expect(announced()).toContain(...))`. Fluent's announcer writes each message as `innerText` on a span of its own, which jsdom keeps as a property, and its clearing is ignored, so the newest is the last span; read from the first, a second message read as the first. Use it rather than a copy in the test (13 copies were folded into it, 2026-10-21).
## Writing tests
- **`jest.mock(...)` must precede the import statements.** Heft runs Jest on TypeScript's CommonJS output without Babel, so mocks are not hoisted; only statement order puts them first.
- Usage statistics: the helpers in `pp365-shared-library/lib/telemetry/__fixtures__/testFixtures`. `startTestTelemetry()` in `beforeEach` opens the gate; `countedTelemetry()` returns what was counted, usage keyed `'<component> <event> <variant>'` and errors `'<component> <code> <http>'` (the site type is in the store, not the key); `telemetryTestBed()` captures what is sent; `hubPortal`, `settingsMap` and `spfxTestContext` give the anchor and the context. A test of a counted action asserts that it counts once, and nothing when the action fails (`.development-guide/spfx/bruksstatistikk.md`).
- Unit: next to the code, `foo.test.ts`. Never import `@pnp/*` in a test; test against structural stand-ins (`shared-library/src/services/EntityPortalService/pnpShapes.ts`) or mock the adapter with `jest.mock`.
- Component: `@testing-library/react` 16 with `@testing-library/dom` 10 (React 18), `@testing-library/user-event` for interaction. Testing Library's `render` wraps itself in `act`; a test that mounts through `renderReact` (a `createRoot`, which renders after the call returns) wraps the call in `act`, as `shared-library/src/util/reactRoot.test.tsx` does. Data comes from a hook or adapter, so `jest.mock('./useX', ...)`. `.module.scss` classes resolve to their names. Strings are the Norwegian texts. Pattern: `ProjectWebParts/src/components/ProjectStatus/Header/Header.test.tsx`; shared-library `LoadingSkeleton.test.tsx`.
- Fluent v9's first load costs 15-45 s per test file: group a feature's tests in one file rather than one file per tiny component.
- A test's time limit is 30 s (`testTimeout` in `pp365-jest-config`), not Jest's 5 s: CI runs two solutions' builds at once, and tests of 1-2 s locally failed there at random on 5 s, one a run, a different one each time (2026-10-19). Do not give a test its own lower limit; a hang still fails. A test that opens a real Fluent v9 menu may get a higher one as `it`'s third argument: opening the menu took some 24 s under jsdom on a loaded machine, and CI went past 30 s (`ProjectMenu.test.tsx`, 2026-11-10).
- Fluent v9 menus: user-event's pointer sequence on a menu item stalls the jsdom worker for minutes; use `fireEvent.click`. A nested menu cannot be opened under jsdom: assert the trigger (`aria-haspopup="menu"`) and read the choices from the hook that builds them. Each open menu costs tens of seconds of teardown, growing per menu: render one per file.
- Extensions and web parts are tested as classes: create the instance, assign `context`, `properties` (and a web part's `domElement`) as SharePoint does, call `onInit`. The stub's base classes are ES5 constructor functions, as SPFx's are: an ES5 subclass cannot call a native `class` ("Class constructor ... cannot be invoked without 'new'"). `BaseDialog.show()` renders after the current task and resolves when the dialog closes; `onAfterClose` runs after the close, as in SPFx. Examples: `PortfolioExtensions/src/extensions/*/*.test.ts`, `ProjectExtensions/src/extensions/projectSetup/projectSetup.test.ts`, `ProgramWebParts/src/webparts/*/*.test.tsx`.
- Every `@microsoft/sp-*` package maps to one stub file and every `@pnp/*` to another, so a `jest.mock` of one is a mock of all of them in that file. To replace one value (say `spfi()` handing out the test's stand-in), wrap the stub in a `Proxy` that overrides only that value, as `PortfolioExtensions/src/extensions/ideaProcessing/ideaProcessing.test.ts` does.
- Stub values are chainable proxies. Jest takes anything with a function-valued `asymmetricMatch` for a matcher, so both stubs answer `undefined` there (otherwise `expect.anything()` and any equality with a stub value fail). `LogLevel` of `@pnp/logging` has its real numbers.
- `heft test` without `--clean` leaves a deleted test's compiled file in `lib-commonjs`, and runs it: remove a throwaway test's output from `lib` and `lib-commonjs` too, or count the files Jest reports.
- Code reading the SPFx build constant `DEBUG` needs `;(globalThis as any).DEBUG = false` in the test, above the imports when the module reads it at load.
- Inside an open Fluent drawer (`BasePanel`) the entry motion never finishes under jsdom, so `toBeVisible()` fails for everything in it: check the attribute that hides an element instead (`element.closest('[hidden]')`). Role queries skip hidden elements; `{ hidden: true }` includes them.
- Fluent v8 is left only inside PnP's controls (`ModernTaxonomyPicker`, property-pane fields), which read the key from `keyCode`/`which`: `fireEvent.keyDown(element, { key: 'Escape', keyCode: 27, which: 27 })`.
- `new Image()` never loads under jsdom; code that preloads an image is tested with a stand-in `window.Image` that calls `onload` or `onerror` (`shared-library/src/components/ProjectLogo/ProjectLogo.test.tsx`).
- jsdom cannot navigate: `location.reload()` and `location.href = ...` report "Not implemented: navigation" through `console.error` and the code runs on past them. Swallow only that message (`ignoreNavigation` in `PortfolioExtensions/src/extensions/testFixtures.ts`) and assert what was written before the navigation.
- The combobox family (`Combobox`, `Dropdown`, `TagPicker`) looped endlessly under jsdom on React 17 the moment it opened; on React 18 it opens and picks (probed 2026-10-07), but one opening took 40-60 s on a loaded machine, so tests keep standing in for it. A test that must choose stands in for `Combobox` and `Option` with a native `<select>` keeping Fluent's contract (`onOptionSelect` gets the option's value and text), as `PortfolioExtensions/src/components/IdeaApprovalDialog/IdeaApprovalDialog.test.tsx` does. A test that types into a `TagPicker` uses the harness's stand-in: `jest.mock('@fluentui/react-components', () => jest.requireActual('pp365-jest-config/lib/tagPickerStandIn').withTagPickerStandIn())` (see `PeoplePicker.test.tsx`). It renders a tag's and an option's `media`, so a picture counts in their accessible names as it does in the browser.
- In a `TagPicker` the picked tags have the `option` role too. A browser test that picks a search result finds it by something only results show, such as the email (`e2e/tests/flows/people-picker.spec.ts`).
- A bundled Fluent icon (`bundleIcon`, `getFluentIcon`'s default) renders two `svg`s, the filled and the regular, one hidden by a class: assert an icon by its colour or name, not by counting `svg`s (`TrendColumn.test.tsx`).
- `getByRole` computes the whole document's accessibility tree, seconds per call in a large Fluent tree (an open popover or dialog over the web part): use `getByText`/`getByTitle`/`getByLabelText` there, roles where the tree is small.
- A button inside a Fluent `Tooltip`: user-event's click moves the pointer onto it, which opens and positions the tooltip, and that stalled a test past 30 s in CI though it passed locally (`List.test.tsx`, the expand-all button, 2026-10-19). Where the click is what is under test, use `fireEvent.click`.
- Opening a Fluent v9 popover positions it against its trigger, which under jsdom cost 13 s per test locally, over a minute in CI. A test that opens one stands in for `Popover`/`PopoverTrigger`/`PopoverSurface` with a plain popover keeping Fluent's contract (trigger toggles through `onOpenChange`, surface shows while open), as `ProjectWebParts/src/components/ProjectPhases/ProjectPhases.test.tsx` does; or render the surface's content directly.
- "The `document` global was defined when React was initialized, but is not defined anymore" means a component kept doing async work (popover positioning, timers) after its test ended, and it takes the whole Jest worker down: `afterEach(async () => { cleanup(); await act(() => new Promise((r) => setTimeout(r, 50))) })`.
- The hub's `List` (PortfolioWebParts) renders its rows on Fluent v9's `Table` (`List/ListGrid`): filter out the selection column's nameless `columnheader`, and find item rows by their check (`strings.ListSelectRowLabel`), as group rows have their own; see `components/List/List.test.tsx`. `WebPartTitle` renders one `<h2>` with the title in a span, and an info button named «Informasjon om <title>» (#1788): query `getByRole('heading', { level: 2, name })`, or `getByText(title, { selector: 'span' })` in a large tree.
- SPFx context: pass a minimal object with exactly the fields the component reads. Do not build a general SPFx mock.
- Dates: a Jest test cannot move the machine's time zone. `process.env.TZ = '…'` inside a test writes to Jest's copy of the environment and changes nothing (such a test passed on an Oslo machine for the wrong reason), while real Node applies it at once to `Date`'s local fields and `toLocaleString`. So a Jest test varies the *site's* zone instead, with `setPageContextInfo({ webTimeZoneData })` and the fixtures in `shared-library/src/util/testFixtures.ts` (Honolulu lies west of any machine the suite runs on, Tokyo east of CI's UTC and Oslo), restored in `afterEach`; the machine-zone matrix runs where `TZ` takes effect: `shared-library/test/runtime/dates.runtime.test.mjs` (`node --test`) and `integration/tests/project-properties.test.ts`. The case to cover: a date-only value stored as the site's midnight, read in a zone west of the site, is the day before.
- The Excel export runs the real SheetJS: `ExcelExportService.test.ts` (CommonJS build) reads the saved file back. Only `e2e/tests/smoke/portfolio.spec.ts` covers the browser's ES module build: it downloads the hub overview's export and checks for an xlsx package (skipped when the "Vis eksport til Excel-knapp" property is off).
- E2E folders: `tests/smoke` (read-only); `tests/flows` (in CI; four of six write to the tenant, clean up after themselves (REST helpers in `tests/fixtures/rest.ts`), and skip without the admin or manage rights they need); `tests/local` (never in CI: `E2E_LOCAL_BUNDLE=1` plus a dev server, loading the local bundle through debug manifests; see `e2e/README.md`); `tests/diagnostics` (never in CI: `E2E_PLACEHOLDER_DIAGNOSTICS=1`; measures SharePoint for a report to Microsoft, the footer's placeholders on list pages for sp-dev-docs#11070, with the footer's own trace on (`pp365.debug.placeholders`); asserts nothing, repeats a load that had to sign in, and writes `e2e/placeholder-diagnostics/<time>/`; the trace's `connected` says whether the content SharePoint handed the footer was in the page, which `acquired` alone does not).
- E2E accessibility scans in `e2e/tests/fixtures/a11y.ts`: `scanAccessibility(page, { component, include, exclude })` runs axe over our markup (web parts by `channelWebPartsOnPage(page)`, surfaces by `SURFACES`), attaches `axe-<component>.json`, notes an `a11y` annotation, and fails only for components in `A11Y_BLOCKING`; Fluent's Tabster sentinels are left out (`FLUENT_INTERNALS`). The pages are listed in `tests/fixtures/pages.ts`: `tests/smoke/a11y-baseline.spec.ts` scans them and `a11y-visual.spec.ts` measures them (reports only). `a11y-surfaces.spec.ts` opens the surfaces no other spec opens, read-only, and soft-asserts the focus back after Escape, so one run reports them all. When a component turns blocking: pp365-a11y.
- E2E fixtures in `e2e/tests/fixtures/pp365.ts`: `openPage` (retries a network-level failure once, reports a 404 with its URL, fails on a web part's error boundary, "Noe gikk galt"/"Something went wrong", and fails when a PP365 web part on the page is another release channel's component than `E2E_CHANNEL`, default `test`, or a PP365 web part, by the alias in its feature tag, whose id no channel file knows: such a page runs that channel's or package's code, as three of the test hub's aggregated overviews, its dynamic list and the project's timeline did until 2026-10-09, and a matrix page with a 1.8.1 package's web part did on 2026-10-14; the tenant's app catalog offers every package's components in the toolbox, so a page made by hand or by script must take the channel's ids from `channels/<name>.json`), `resolvePage(site, candidates)` (finds the page in the site's SitePages via REST, skips listing the existing pages when none matches), `onListPage(page, url, step)` (opens a library or list view and runs `step`; when the step fails after SharePoint's React fault on list pages, sp-dev-docs#11068, it reloads once and runs it again, since a reload has a warm cache and the CI retry a cold one; give such a test room with `test.setTimeout`), `webPart(page, text)`, `webPartByAlias(page, alias)` (matches `data-sp-feature-tag`), `WEB_PART` = `[data-sp-web-part-id]` (the one marker canvas and app pages share), `configuredUrl` (ignores `.env.example` placeholders), and a console guard failing on missing-module errors (SharePoint's CSP noise ignored). The fixture's `test` also guards every browser context against usage statistics (`guardTelemetry`: the session flag `PP_DISABLE_TELEMETRY` = `1` in every page, and 204 in Assist's place for `assist.prosjektportalen.no/api/telemetry/**`), so no run reaches Assist: a context a test makes itself with `browser.newContext`, and the two setup steps, call it by hand. Only `tests/smoke/usage-statistics.spec.ts` turns it off (`test.use({ telemetryGuard: false })`), captures the batch and checks it against the contract and the never-list at the hub's level (its own copy of the field allowlist: a new field goes there too); the hub's settings as the code reads them come from `hubSettings`/`hubSetting` in `fixtures/rest.ts` (enabled rows, exact key, the row read last). Sign-in in `tests/auth.setup.ts` with `E2E_USERNAME`/`E2E_PASSWORD`; then the `deployment` project (`tests/deployment.setup.ts`) waits, at most ten minutes, until the hub and the project home load every bundle from the app catalog (after an upgrade SharePoint can still serve a component's previous manifest: "Could not load ... in require"). `E2E_BASE_URL` is the hub; `E2E_PROJECT_URL` and `E2E_PROGRAM_URL` (CI variables too) a provisioned project and program, whose tests skip without them; `E2E_PAGE_*` override page names. No template page holds the matrix web parts: `tests/smoke/matrices.spec.ts` reads the status page's uncertainty section and a project page with both web parts (`E2E_PAGE_MATRIX`, else `Usikkerhet.aspx`), added with `npm run add-matrix-page -- <project url>` in `integration/` (PnPjs creates and publishes it with the toolbox defaults), and skips with the reason until it exists. Use the `playwright-cli` skill (`references/test-generation.md`) to plan, generate and heal specs.
- E2E waits and navigations: wait for a list's data, not its first row. The portfolio overview draws placeholder rows from the columns persisted in local storage while the data loads ("Viser 0 av 0"), so wait for the results counter (`[class*="resultsCount"]` with a non-zero count, as `columnHeaders` does) or for text in a body cell (`measureListTypography`), and for the element itself when a renderer swaps in later (the overview's title cells get their panel button seconds after the rows, once the view's own columns replace the persisted ones); a test that counted the title buttons at the first row skipped on every run, and one that measured after a fixed pause was flaky. Repeat a flaky test with CI's `--workers=2`: with the default workers and `--repeat-each=3`, twelve heavy pages at once made the web parts themselves fail ("Ingen konfigurasjon tilgjengelig"). Lists grouped by hub (the program administration and its add dialog) open only groups of fewer than ten, so open them all (`Vis alle grupper` / `Expand all groups`) before measuring or scrolling a list. A navigation outside `openPage` (a library view, the quick launch's pages, the sign-in) goes through `withNetworkRetry(() => page.goto(...))`, which sends it once more after a network-level failure (`net::ERR_TIMED_OUT`); only `deployment.setup.ts` keeps its own ten-minute loop. Measuring a Fluent toolbar's or menu's children, leave out `[data-tabster-dummy]`: Tabster's focus guards are 1 px `i` elements at the page's top left (the toolbar layout test read them as an item 368 px off the line). The visual test (`a11y-visual.spec.ts`) tells text cut off apart from text that ends in «…» (`cutOff`, `endsInEllipsis`); only the first needs a look. A REST call goes through `restGet`/`restPost` (or `withSessionRenewal` in `fixtures/pp365.ts`): SharePoint may stop accepting the stored session mid-run (401/403 on every REST call while pages still load, 2026-10-20; since 2026-10-27 about ten minutes after sign-in, with `rtFa` refused too), and those load the site in a tab of their own, wait until Entra ID's sign-in has brought the tab back to the site (closing it as `goto` returned cut the sign-in off: run 40533981903, 26 tests), and send the call once more. A skip is a claim about the tenant's data: when a test skips on every run, find out whether the data is really missing before accepting it. So is a count of 0: the date test checked 0 of 1 fields for days because its REST query selected only the texts, and `FieldValuesAsText` expanded on list items holds only the fields the query also selects (with Created and Modified). The browser errors attached to every test (`pageerror: undefined`, rejections from `loadAllAsync`) are SharePoint's own page assembly and list bundle, traced with the debugger on 2026-10-19.
- E2E secrets: never type one with `fill()`, `type()`, `pressSequentially()` or `insertText()`. Playwright titles the step `Fill "<value>"`, the HTML report keeps every step of every test, passed ones too, and Playwright 1.63 redacts nothing: until 2026-10-14 every CI report held the test user's password. Use `enterSecret` in `e2e/tests/auth.setup.ts` (`fill('')`, then Chromium's `Input.insertText` through a CDP session: trusted input, and a protocol call is no report step; wrapping `fill()` in `test.step`, boxed or not, still reports the inner title). A failed test's `error-context.md` ARIA snapshot holds every input's value, password fields too: the setup's `afterEach` blanks them first, and the public artifact leaves `test-results/auth.setup*` out. A trace keeps every action's arguments, the page's input values and the session's cookies, so the `setup` project runs with `trace: 'off'` (CI; `--trace on` and UI mode override it locally) and the public artifact leaves traces out.
## Integration tests (`integration/`)
The shared library's data layer in Node against the test tenant, asserting on what SharePoint returns and stores (`docs/plans/integration-tests.md`, `integration/README.md`).
- Harness, one concern per file in `integration/src`: `env` (configuration, `skipReason`), `auth` (sign-in), `loader` (`module.registerHooks`, as Jest's `moduleNameMapper`/`moduleDirectories`: `pp365-*`, their `lib` folder and its paths to `lib-commonjs`, so there is one instance of the library and the tests' sign-in reaches a solution's clients; a solution's bare imports of its own folders in its `lib-commonjs`; the string modules each package names in `config/config.json` in `INTEGRATION_LOCALE` through `pp365-jest-config/lib/amdTransform.js`; `@microsoft/sp-*` to `spfxStub.js`, `sp-lodash-subset` to `lodashSubset.js`, PnP's UI controls `@pnp/spfx-controls-react`/`-property-controls` to `pnpStub.js` (webpack-only ESM; the rest of `@pnp/*` stays real); stylesheets to class names), `globals` (jsdom's `DOMParser` and `XMLSerializer`, and `_spPageContextInfo` with the locale's cultures), `context` (the stand-in SPFx context), `sites` (`connect(url)`, `appOnlyDenied`), `library` (the library's `lib-commonjs` modules and ProjectWebParts' adapter, typed by `lib`). Loading a solution's barrel (`pp365-shared-library`) pulls in the whole library with Fluent: about 6 s once per file.
- The library's clients reach the tenant through `setSpfiFactory` (`shared-library/src/data/createSpfiInstance.ts`), which `sites.ts` registers once; without it `createSpfiInstance` is `SPFx(context)` as before. `SpEntityPortalService` goes through the same path and takes `origin` from the context's web, not `window`.
- Sign-in: `certificate` (CI: `CI_TENANT`, `CI_CLIENT_ID`, `CI_CERT_BASE64`, app-only, MSAL with the PFX read in memory, with an empty password or none) or `cookies` (locally: `e2e/.auth/user.json`, with `RequestDigest` for writes and a `Mozilla/5.0` User-Agent, without which the term store's v2.1 API refuses cookies: "OAuth only flow is enabled"). `INTEGRATION_AUTH` forces one. App-only the library's user is `INTEGRATION_USER`. Search and REST answer the CI app; the term store refuses it (403) until it has `TermStore.Read.All` (SharePoint, application). A test needing a permission the app may lack probes with `appOnlyDenied(site, probe, permission)` from `src/sites.ts`, which skips app-only on 403 and never with cookies.
- A test: `describe(name, { skip: skipReason('hubUrl') }, ...)`, then `const hub = await connect(env.hubUrl!)` and a service from `src/library.ts` configured with `hub.context`. A missing site or sign-in skips with the reason; `INTEGRATION_STRICT=true` (CI) throws it instead. `INTEGRATION_LOCALE` must match the sites' language (`context.ts` throws otherwise): the services find hub lists by their titles in the strings' language.
- Writes only to `INTEGRATION_PROJECT_URL` and to hub rows the test created, restored in `finally` from what it read first; never to `E2E_PROJECT_URL`. Assert what SharePoint returned or stored, read back, independent of time zone and other projects' data. No token, cookie or certificate in a log, report or file.
- Erasable TypeScript only (no `enum`, namespaces, parameter properties; `import type` for types); imports name the `.ts` file. Deep PnPjs imports take `.js` (`'@pnp/sp/presets/all.js'`): Node's ESM resolution needs it, and without the preset `sp.web`/`sp.search` are missing from the type. The tsconfig is `bundler`, not `nodenext`: PnPjs 4's typings augment `SPFI` through `declare module "../fi"`, which nodenext cannot resolve. Format with `SharePointFramework/.prettierrc.yaml`.
- Tests per area in `integration/tests`: `harness` and `html-reporter` (offline), `reachability`, `portal-data-service`, `search`, `term-store`, `project-properties` (writes the reserved project's properties item), `hub` (its hub row, a test column), `status-reports` (a draft in the reserved project's report series `ITEST`), `template` (the upgrade's result), `project-web-parts` (ProjectWebParts' `SPDataAdapter`: the sync to the hub, the matrix's data source on the program), `multi-hub` (the hubs `AvailableProgramHubs` names, a second hub read as the merged view reads one, and the program administration's one search over every hub; `INTEGRATION_SECOND_HUB_URL`, a repository variable too, read only). ProjectExtensions' `SetupProjectInformation` stays out: its list sync is JSOM (I10) and its hub row needs a new site per run.
- `npm run build` type-checks (`tsc --noEmit`); the CI job runs `npm run test:ci` (spec to the log, JUnit to `test-results/junit.xml`, HTML to `test-results/index.html` from `src/reporters/html.ts`, a `node:test` reporter that embeds its totals as `<script type="application/json" id="report-summary">` for the site; Node's `MaxListenersExceededWarning` with three reporters is harmless), uploads `test-results` as the artifact `integration-report-test-channel` and publishes the HTML report to the test report site (`.tasks/publish-test-report.js`: a private GitHub Pages site in another repository, `TEST_REPORTS_REPOSITORY`; setup in the CI chapter «Testrapportsiden»). It installs `--to pp365-integration --to pp365-templates` and runs `generate-resx-ts` before building the library (`src/loc/shared` is generated, not in git), then compiles ProjectWebParts' `lib-commonjs` with `tsc --noCheck` and copies its `src/loc` bundles beside it. Locally both builds must be current: `npx heft build --clean` in `shared-library` and `ProjectWebParts` after a change there.
## When a test fails
- In a build: the build stops. Reproduce with `npm test` in the solution, decide code vs test, fix the code for regressions; update the test in the same commit only for intentional behaviour changes. Never delete an assertion to go green.
- Integration: the job log prints each test and its assertion. The HTML report (each file's tests, errors with cause chain and stack, diagnostics, the file's output) is on the test report site: the «Integration report» link in the job summary, 7 days. Fallback, without the site: `gh run download <run-id> -n integration-report-test-channel`, then open `index.html`. Environment (the app's permissions, a missing variable: `INTEGRATION_STRICT` makes it fail, not skip) → fix and rerun. Regression → fix the code; the failing test names one function. A changed SharePoint response → fix the reading code, and let the test pin the new shape. `node:test` has no retries.
- E2E: the job log lists each test and prints the assertion and locator per failure (`github` reporter). Full report, traces included: the test report site, the «End-to-end report» link in the job summary (7 days). Fallback, without traces (the repo is public, so anyone signed in to GitHub can download its artifacts, and a trace holds the test user's cookies): the `playwright-report-test-channel` artifact (7 days, the repo's maximum), `playwright-report/` (HTML) and `test-results/` (`error-context.md` page snapshot, screenshot, video, `junit.xml`, `results.json`). Fetch and open from `e2e/` with `gh run download <run-id> -n playwright-report-test-channel -D ci-report && npx playwright show-report ci-report/playwright-report`. Environment (sign-in, MFA, missing page) → fix secret/policy/variable and rerun. Regression → issue labelled `bug` (there is no `e2e` label) with the run link; release blocked. Intentional UI change → heal the spec in its own commit. One CI retry exists; three consecutive flaky runs → `test.fixme` plus an issue, not more retries.
## Do not
- Do not add `@pnp/*` transforms or try to load PnPjs in Jest without updating `pp365-jest-config` and this skill.
- Do not change `pp365-jest-config` without running `heft test` in `shared-library` and one consumer.
- Do not write to a site but `INTEGRATION_PROJECT_URL` in an integration test, print a secret, or make `pp365-integration`'s `build` run the tests (`rush build` must not need a tenant).
- Do not put Jest tests under `lib/`, `temp/` or outside `src/`; Heft only compiles `src/**`. (`shared-library/test/runtime` holds `node --test` files, outside `src` on purpose.)