Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/workflows/safe-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,17 @@ jobs:
persist-credentials: false
- uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af
with:
node-version: '18'
node-version: '20'
cache: 'npm'
cache-dependency-path: src/vertex/package-lock.json
- name: Install dependencies
run: cd src/vertex && npm ci
- name: Lint
run: cd src/vertex && npm run lint --if-present
- name: Type Check
run: cd src/vertex && npx tsc --noEmit
- name: Test & Coverage
run: cd src/vertex && npm run test:coverage
Comment thread
Codebmk marked this conversation as resolved.

check-platform:
needs: detect-changes
Expand Down
7 changes: 7 additions & 0 deletions src/vertex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ npm run dev
- `npm run format`: Format code with Prettier.
- `npm run format:check`: Check formatting.
- `npm run check-size`: Build and run bundle size checks.
- `npm run test`: Run the Vitest test suite once.
- `npm run test:watch`: Run Vitest in watch mode.
- `npm run test:coverage`: Generate Vitest coverage reports.

## Testing

Vertex uses Vitest and React Testing Library for unit, hook, and component tests. Follow the internal testing conventions in `app/_docs/internal/TESTING.md` when adding or updating tests.

## Environment variables

Expand Down
219 changes: 219 additions & 0 deletions src/vertex/app/_docs/internal/TESTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
# Testing Guide

This guide defines the testing conventions for Vertex. Follow it when adding or updating automated tests.

## Test stack

- Vitest is the test runner.
- React Testing Library is used for React components and hooks.
- `@testing-library/jest-dom` matchers are loaded globally from `vitest.setup.ts`.
- The default test environment is `jsdom`.
- Do not add Jest.

## Commands

Run the full unit/component suite once:

```bash
npm run test
```

Run tests in watch mode while developing:

```bash
npm run test:watch
```

Generate coverage:

```bash
npm run test:coverage
```

Run TypeScript validation:

```bash
npx tsc --noEmit
```

Before opening a PR that adds or changes tests, run:

```bash
npm run test
npx tsc --noEmit
```

## File organization

Use co-located test files for unit, hook, and component tests.

```txt
core/utils/status.ts
core/utils/status.test.ts

core/hooks/useClipboard.ts
core/hooks/useClipboard.test.tsx

components/ui/Button.tsx
components/ui/Button.test.tsx
```

Use:

- `*.test.ts` for TypeScript utilities and non-JSX logic.
- `*.test.tsx` for React components, hooks, providers, and tests that render JSX.

Do not create `tests` folders under every feature or utility folder for unit tests. Co-location keeps tests close to the behavior they protect and makes future service/module migrations safer because source files and tests move together.

Use a shared root-level `test/` folder only for reusable test infrastructure when needed:

```txt
test/
factories/
mocks/
utils/
```

End-to-end tests should live separately under an `e2e/` folder when Playwright is introduced.

## Writing good tests

Test public behavior, not private implementation details.

Prefer assertions that describe what a user, caller, or consuming module observes:

- returned values
- rendered accessible UI
- emitted events
- storage updates
- error messages
- callback behavior

Avoid assertions that depend on:

- private helper functions
- internal state shape unless it is the public contract
- exact CSS classes, except where the class string is the actual utility output
- snapshots for utility tests

Use table-driven tests when a function has repeated input/output cases.

## Utility tests

Utility tests should be small, deterministic, and focused.

Cover:

- happy paths
- boundary values
- empty, nullish, or malformed inputs where supported
- error branches
- real regression cases

For date or time logic:

```ts
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-06-28T12:00:00.000Z"));
});

afterEach(() => {
vi.useRealTimers();
});
```

For browser storage logic:

```ts
beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
});

afterEach(() => {
localStorage.clear();
sessionStorage.clear();
});
```

Use real `jsdom` storage or the shared setup fallback. Do not manually mock storage inside each test file unless a specific failure mode must be simulated.

## Hook and component tests

Use React Testing Library and test behavior through rendered output or hook results.

Prefer:

- `screen.getByRole`
- `screen.getByLabelText`
- `screen.getByText`
- `userEvent` for interactions

Avoid:

- querying by implementation-specific selectors
- testing React internals
- asserting on state setters directly

When hooks/components need providers, use shared render helpers rather than duplicating wrapper setup in every file.

Recommended future helpers:

```txt
test/utils/renderWithProviders.tsx
test/utils/renderHookWithProviders.tsx
test/factories/
test/mocks/
```

## Mocking guidance

Mock at boundaries, not everywhere.

Good mock boundaries include:

- network clients
- NextAuth session state
- Next.js router/navigation APIs
- timers
- browser APIs not implemented by jsdom

Avoid mocking the function under test or its private helpers.

Keep mocks local to the test file unless they are reused across multiple domains. Shared mocks should live under `test/mocks/`.

## Coverage expectations

Coverage should be used as a quality signal, not as a substitute for useful assertions.

Prioritize meaningful coverage for:

- core utilities
- hooks
- shared UI components
- service/API boundary logic
- permission and access-control logic

Do not add low-value tests just to increase coverage numbers.

## Deferred test areas

Proxy and network-heavy utilities should be tested in a later integration-style pass with explicit mocks for axios, NextAuth, environment config, and Next.js request/response objects.

Examples:

- `core/utils/proxyClient.ts`
- `core/utils/secureApiProxyClient.ts`
- `core/utils/platform.ts`

## PR checklist

When adding or changing tests, confirm:

- Tests are co-located with the source file.
- Test names describe behavior.
- Tests are deterministic and do not leak timers or storage state.
- No snapshots were added for utilities.
- `npm run test` passes.
- `npx tsc --noEmit` passes.
119 changes: 119 additions & 0 deletions src/vertex/core/utils/clientCache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
runClientCacheMaintenance,
shouldEnablePersistentClientCache,
} from "./clientCache";

const VERSION = "2026-04-30.1";
const VERSION_KEY = "airqo:vertex:client-cache:version";
const QUERY_CACHE_PREFIX = "airqo:vertex:react-query:";
const MISMATCH_LOG_KEY = "airqo:vertex:cache-version-mismatch:last";

describe("clientCache utilities", () => {
beforeEach(() => {
window.localStorage.clear();
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-06-28T12:00:00.000Z"));
});

afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
window.localStorage.clear();
});

it("reports that persisted client cache is enabled", () => {
expect(shouldEnablePersistentClientCache()).toBe(true);
});

it("does nothing when the cache version already matches", () => {
window.localStorage.setItem(VERSION_KEY, VERSION);
window.localStorage.setItem(`${QUERY_CACHE_PREFIX}devices`, "cached");

runClientCacheMaintenance();

expect(window.localStorage.getItem(`${QUERY_CACHE_PREFIX}devices`)).toBe(
"cached"
);
expect(window.localStorage.getItem(MISMATCH_LOG_KEY)).toBeNull();
});

it("removes persisted react-query cache entries when the version changes", () => {
window.localStorage.setItem(VERSION_KEY, "old-version");
window.localStorage.setItem(`${QUERY_CACHE_PREFIX}devices`, "remove-me");
window.localStorage.setItem(`${QUERY_CACHE_PREFIX}sites`, "remove-me");
window.localStorage.setItem("unrelated", "keep-me");

runClientCacheMaintenance();

expect(window.localStorage.getItem(`${QUERY_CACHE_PREFIX}devices`)).toBeNull();
expect(window.localStorage.getItem(`${QUERY_CACHE_PREFIX}sites`)).toBeNull();
expect(window.localStorage.getItem("unrelated")).toBe("keep-me");
expect(window.localStorage.getItem(VERSION_KEY)).toBe(VERSION);
expect(window.localStorage.getItem(MISMATCH_LOG_KEY)).toBe(
"2026-06-28T12:00:00.000Z"
);
});

it("sets the cache version on first maintenance run", () => {
runClientCacheMaintenance();

expect(window.localStorage.getItem(VERSION_KEY)).toBe(VERSION);
});

it("tolerates localStorage remove failures while continuing maintenance", () => {
const fakeLocalStorage = {
getItem: (key: string) => {
if (key === VERSION_KEY) return "old-version";
return null;
},
setItem: vi.fn(),
removeItem: vi.fn(() => {
throw new Error("storage unavailable");
}),
length: 1,
key: (i: number) => (i === 0 ? `${QUERY_CACHE_PREFIX}devices` : null),
};

const originalLocalStorage = window.localStorage;
Object.defineProperty(window, "localStorage", {
value: fakeLocalStorage,
configurable: true,
});

expect(() => runClientCacheMaintenance()).not.toThrow();
expect(fakeLocalStorage.removeItem).toHaveBeenCalledWith(
`${QUERY_CACHE_PREFIX}devices`
);

Object.defineProperty(window, "localStorage", {
value: originalLocalStorage,
configurable: true,
});
});

it("tolerates localStorage write failures", () => {
const fakeLocalStorage = {
getItem: () => null,
setItem: vi.fn(() => {
throw new Error("storage unavailable");
}),
removeItem: vi.fn(),
length: 0,
key: () => null,
};

const originalLocalStorage = window.localStorage;
Object.defineProperty(window, "localStorage", {
value: fakeLocalStorage,
configurable: true,
});

expect(() => runClientCacheMaintenance()).not.toThrow();
expect(fakeLocalStorage.setItem).toHaveBeenCalledWith(VERSION_KEY, VERSION);

Object.defineProperty(window, "localStorage", {
value: originalLocalStorage,
configurable: true,
});
});
});
Loading
Loading