Review application A.4.2

JavaScript tests

The browser code is tested with Jest in a strict JSDOM environment. The tests load the real browser scripts under static/js/ and mock only external libraries such as Leaflet. This is a DOM and unit suite. No suite runs in a real browser, so Leaflet rendering, browser layout, real network timing and visual appearance are not tested, whatever the coverage percentage.

See A4.4 Running the quality checks for combined app/engine checks, module ownership and CI setup, and A4.3 Code quality to interpret the generated evidence.

Run the tests

Use Node 22.x, at least 22.13, matching the supported quality toolchain:

npm ci
npm test -- --runInBand
npm run test:coverage
npm run lint:js
npm run lint:css
npm run vendor:check-cdn

npm test runs the suite without producing coverage artifacts. test:coverage runs all tests in one process, emits reports, then checks that production coverage was actually collected. The coverage command already supplies --runInBand. Do not append Jest options to that compound npm command: they would be passed to the final coverage checker. For a focused Jest run, use:

npm test -- --runInBand tests/js/routes-map.test.js
npm test -- --runInBand --testNamePattern='pagehide'
npm run test:watch

A focused run is useful while editing but does not establish full coverage or refresh the combined quality manifest. Finish with npm run test:coverage, or make quality when the change requires combined application/engine evidence. make quality-fast-container provides lint and focused quality checks in Docker; make quality executes the complete browser suite there as well.

Production-script loading and coverage

All first-party static/js/**/*.js files are part of coverage: components, page controllers and shared scripts. Vendored assets under static/vendor/ are excluded. A production file with no test load remains in the denominator with zero hits.

These scripts publish browser globals through ordered script tags, so tests load them through tests/js/load-browser-script.js. The loader reads the real source, instruments it with Istanbul using its original filename, caches that instrumentation within the suite, and evaluates it in the browser window.

const path = require('node:path');
const loadBrowserScript = require('./load-browser-script');

beforeAll(() => {
    loadBrowserScript(path.join(__dirname, '../../static/js/components/popup-utils.js'));
});

test('invalid serialized route data is treated as empty', () => {
    expect(window.PopupUtils.normalizeRoutes('{invalid JSON')).toEqual([]);
});

Adapt the scenario to the behaviour or invariant being changed. Load a component's production dependencies in their real order, or use load-map-components.js where the existing tests share that setup. A test of one map component on its own loads it with loadMapComponent('<name>') from the same loader, which first clears window.MapComponents. Keep network/map mocks at external boundaries; do not replace the behaviour being tested with a mock implementation.

Do not load production code with ad hoc window.eval(readFileSync(...)) in a test. Jest's normal transform does not instrument that code, so tests would pass while reporting misleading zero coverage. ESLint rejects window.eval(...) calls in the normal test/setup entry points; use the shared loader.

npm run test:coverage writes the Jest results and the Istanbul and LCOV coverage to quality/raw/ (evidence files). It then runs scripts/check-js-coverage.cjs, which fails unless every first-party script is in the coverage and production statements and branches actually executed. Coverage sanity describes the combined check; no coverage percentage fails a run.

Strict browser-error handling

tests/js/strict-environment.cjs fails a test or suite on unexpected console.error, browser errors and unhandled rejections. It allows queued native JSDOM events and promise callbacks to settle before accepting the result. Jest also catches process-level unhandled promise rejections.

A negative-path test may intentionally produce a specific console error. Scope and assert that expectation, and restore the console even if the assertion fails:

test('reports the failed request', async () => {
    const error = jest.spyOn(console, 'error').mockImplementation(() => {});
    try {
        await exerciseExpectedFailure();
        expect(error).toHaveBeenCalledWith('Expected message', expect.any(Error));
    } finally {
        error.mockRestore();
    }
});

exerciseExpectedFailure represents the real page/component action in your test. Do not globally suppress console errors, add broad allowlists, or make the strict environment ignore a recurring failure. An unexpected message may expose a missing mock, but it can also reveal a real production lifecycle bug.

Timers, native events and cleanup

The environment tracks real browser timeouts, intervals and animation frames and rejects work left pending at suite completion. It also rejects pending modern fake timers when a test switches back to real timers or ends the suite. Clearing all timers blindly would hide cleanup bugs; exercise the component's own destroy/pagehide behaviour first and assert the expected state.

beforeEach(() => {
    jest.useFakeTimers();
});

afterEach(() => {
    controller.destroy();
    expect(jest.getTimerCount()).toBe(0);
    jest.useRealTimers();
});

Use jest.advanceTimersByTime(...) for a specific delayed behaviour and await its promise/result. For a cancellation test, run the pending callbacks after calling destroy and verify no stale insertion or request result is applied. Restore any spies, listeners and replaced globals owned by the test.

Native events such as the <details> element's delayed toggle do not necessarily run on Jest's fake clock. A route test must not assume that manually dispatching toggle removes the native queued event. Production teardown removes route listeners and pending resize work; analytics teardown cancels navigation animation and scroll work. Regression tests exercise these cases after pagehide.

tests/js/test-environment.test.js checks the harness itself with one nested Jest run. Each probe is its own test file, so each gets a fresh environment: deliberate console errors, exceptions, rejections and timer leaks must fail, and an asserted expected-error control must pass. The nested run has a 60-second timeout and the setup 70 seconds, to accommodate loaded CI/container hosts. Each probe's status and error message are read from the run's JSON results.

Fixtures and configuration

When a test reports a missing browser global, inspect its dependency setup and production script order. Add an accurate external mock or load the real required helper. Do not add a global declaration merely to silence an actual missing runtime dependency. New tests belong in tests/js/*.test.js; associate them with the appropriate module in the quality catalog when its patterns need updating (Maintain the module catalog).

CI runs this suite, the JS and CSS lint and the vendor check inside the Required quality job (A4.4 CI).

Code

File Role
package.json Test commands, Jest configuration, production roots and report filenames
package-lock.json Resolved dependency tree used by npm ci
tests/js/setup.js Shared presentation-helper loading and Leaflet/application-constant mocks
tests/js/load-browser-script.js Production-source instrumentation and browser evaluation
tests/js/load-map-components.js Shared production map dependencies for page-level tests
tests/js/strict-environment.cjs Unexpected-error detection and browser-work lifecycle checks
tests/js/test-environment.test.js Independent success/failure probes for that environment
scripts/check-js-coverage.cjs Fails unless every first-party script was covered and executed
eslint.config.mjs Conservative correctness rules, classic-script globals and loader enforcement