Compare commits

..

5 Commits

10 changed files with 148 additions and 36 deletions

View File

@@ -9,12 +9,14 @@ paths:
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query.
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check, which walks `getComputedStyle` up the tree on every action; never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.

View File

@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
every interactive element.
5. **Verify** before reporting done:
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
```bash
pnpm tsgo --noEmit
pnpm oxlint src/pages/<Feature>

View File

@@ -34,14 +34,18 @@ You are operating within a constrained context window and strict system prompts.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
- Between gates, after an edit, run at most the one test file that covers it.
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
- Run `pnpm tsgo --noEmit`
- Run `pnpm lint:js --quiet` to find critical errors
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
- Run `pnpm build`
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
- For every test you added or changed, revert the change it covers and confirm the test fails
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
- Fixed ALL resulting errors

View File

@@ -65,6 +65,8 @@ const config: Config.InitialOptions = {
testPathIgnorePatterns: ['/node_modules/', '/public/'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: '<rootDir>/jest.environment.cjs',
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
coverageThreshold: {
global: {
statements: 80,

View File

@@ -144,6 +144,39 @@ window.getComputedStyle = function (
}
};
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs up to ~1 s per open.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
jest.mock('@testing-library/user-event', () =>
jest.requireActual('tests/userEventWithDefaults'),
);
// antd popups walk getComputedStyle up every ancestor to find scroll
// containers on each open. pnpm keeps the package under antd, not at the root.
jest.mock(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
() => ({
...jest.requireActual(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
),
collectScroller: (): HTMLElement[] => [],
}),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());

View File

@@ -30,19 +30,6 @@ jest.mock('@signozhq/ui/sonner', () => ({
},
}));
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs ~1 s per open here, enough to time out under load.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
type AccountSettingsDrawerProps = ComponentProps<typeof AccountSettingsDrawer>;
const onClose = jest.fn() as jest.MockedFunction<

View File

@@ -18,19 +18,6 @@ import {
import { renderListAlertRules, runSearchQuery } from './_helpers';
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs ~1 s per open here, enough to time out under load.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
jest.setTimeout(15_000);
const VIEW_1_ORDER_BY = JSON.stringify({ columnName: 'name', order: 'asc' });

View File

@@ -20,7 +20,7 @@ import MyComponent from '../MyComponent';
describe('MyComponent', () => {
it('renders and interacts', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
server.use(
rest.get('*/api/v1/example', (_req, res, ctx) => res(ctx.status(200), ctx.json({ value: 42 })))
@@ -40,6 +40,8 @@ The full list is [`.claude/rules/frontend-tests.md`](../../../.claude/rules/fron
- Import from `tests/test-utils` only.
- Prefer `userEvent` for real interactions; use `fireEvent` only for low-level events (scroll/resize/setting `scrollTop`).
- One behaviour per test, rendering the smallest component that owns it; each test under 500 ms (`pnpm jest <file> --verbose`).
- Never call `*ByRole` inside `waitFor`; never raise a timeout to make a slow test pass.
- Use MSW to mock network calls; large JSON goes in `mocks-server/__mockdata__`.
- Keep tests type-safe (`jest.MockedFunction<T>`, avoid `any`).
- Find elements by test ID (`getByTestId`, `findByTestId`); role or text only for markup the app doesn't own.
@@ -48,6 +50,7 @@ The full list is [`.claude/rules/frontend-tests.md`](../../../.claude/rules/fron
Repo-specific reasons:
- The harness wires Redux, React Query, i18n, timezone, preferences, so importing from RTL directly bypasses critical providers.
- Some infra deps are globally mocked (e.g., `uplot`) to keep tests fast and stable.
- `jest.setup.ts` turns off user-event's pointer-events check, Floating UI positioning and antd's scroll-container lookup for every test. Each walks `getComputedStyle` up the DOM, which jsdom computes slowly.
- For virtualization (react-virtuoso), there is no `userEvent` scroll helper; use `fireEvent.scroll` after setting `element.scrollTop`.
#### Example patterns (from `components/QuickFilters/tests/QuickFilters.test.tsx`)
@@ -73,7 +76,7 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
Interact via test IDs:
```ts
const user = userEvent.setup({ pointerEventsCheck: 0 });
const user = userEvent.setup();
await user.click(screen.getByTestId('save-changes'));
expect(screen.getByText(/ADDED FILTERS/i)).toBeInTheDocument();
```
@@ -113,5 +116,5 @@ const navigateSpy = mockNavigate(); // module-level navigate()
```
#### Notes
- Global mocks configured in Jest: `uplot` → `__mocks__/uplotMock.ts`.
- Global mocks configured in Jest: `uplot` → `__mocks__/uplotMock.ts`; `@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`.
- If a test needs custom behavior (e.g., different API response), override with `server.use(...)` locally.

View File

@@ -0,0 +1,34 @@
import { render, screen, userEvent } from 'tests/test-utils';
describe('userEvent from the harness', () => {
const onClick = jest.fn();
const renderBlockedButton = (): void => {
render(
<button
type="button"
data-testid="blocked"
style={{ pointerEvents: 'none' }}
onClick={onClick}
>
Blocked
</button>,
);
};
it('skips the pointer-events check for setup()', async () => {
renderBlockedButton();
await userEvent.setup().click(screen.getByTestId('blocked'));
expect(onClick).toHaveBeenCalledTimes(1);
});
it('skips the pointer-events check for the direct API', async () => {
renderBlockedButton();
await userEvent.click(screen.getByTestId('blocked'));
expect(onClick).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,60 @@
type UserEventModule = typeof import('@testing-library/user-event');
type UserEvent = UserEventModule['default'];
type DirectMethod = Exclude<keyof UserEvent, 'setup'>;
const actual = jest.requireActual<UserEventModule>(
'@testing-library/user-event',
);
const userEvent = actual.default;
// The pointer-events check walks getComputedStyle up the tree on every action.
const DEFAULTS = {
pointerEventsCheck: actual.PointerEventsCheckLevel.Never,
};
// Position of the options argument in each direct API call.
const OPTIONS_INDEX: Record<Exclude<DirectMethod, 'clear'>, number> = {
copy: 0,
cut: 0,
tab: 0,
click: 1,
dblClick: 1,
tripleClick: 1,
hover: 1,
unhover: 1,
keyboard: 1,
pointer: 1,
paste: 1,
deselectOptions: 2,
selectOptions: 2,
type: 2,
upload: 2,
};
const withDefaults =
(name: DirectMethod, optionsIndex: number) =>
(...args: unknown[]): Promise<unknown> => {
const next = [...args];
next[optionsIndex] = {
...DEFAULTS,
...(next[optionsIndex] as object | undefined),
};
return Reflect.apply(userEvent[name], userEvent, next);
};
const directApi = Object.fromEntries(
Object.entries(OPTIONS_INDEX).map(([name, index]) => [
name,
withDefaults(name as DirectMethod, index),
]),
);
const userEventWithDefaults: UserEvent = {
...userEvent,
...directApi,
clear: (element) => userEvent.setup(DEFAULTS).clear(element),
setup: (options) => userEvent.setup({ ...DEFAULTS, ...options }),
};
export const { PointerEventsCheckLevel } = actual;
export default userEventWithDefaults;