Jest fixes 24

This commit is contained in:
karilint
2026-03-18 15:53:18 +02:00
parent b0e4868dfd
commit 51b02b15cf
3 changed files with 119 additions and 0 deletions
+92
View File
@@ -0,0 +1,92 @@
# AGENTS.md
Repository-specific instructions for Codex sessions in this repository.
These instructions apply to all work in `nowdatabase_react` unless the user gives a more specific direct instruction for the current task.
## Source Policy Files
Codex must follow the repository policies described in:
- `documentation/codex_planning_prompt.md`
- `documentation/coding_prompt_template_fullstack.md`
Treat those files as the canonical planning and coding policy for this repository.
## How To Handle User Requests In VS Code
- The user may describe tasks in plain language in the Codex chat panel.
- Do not require the user to provide JSON task payloads.
- Translate the user’s plain-language request into the same planning and implementation discipline described in the two policy files above.
- If the request is ambiguous in a way that could cause incorrect implementation, ask a short clarifying question. Otherwise make reasonable assumptions and proceed.
## Default Workflow
For any non-trivial feature, bug fix, refactor, or test change:
1. Read the relevant code before changing anything.
2. Create a short internal plan that follows `documentation/codex_planning_prompt.md`.
3. Implement the task using the coding standards from `documentation/coding_prompt_template_fullstack.md`.
4. Run the relevant validation commands.
5. Summarize what changed, what was verified, and any remaining risks.
For very small requests, Codex may skip writing out a formal plan, but it must still follow the same policy.
## Frontend Test Policy
When changing frontend code or frontend tests, Codex must proactively apply these rules:
- Prefer narrow fixes over broad Jest configuration workarounds.
- Before changing Jest config, check whether the real issue is missing runtime context in tests.
- Wrap Redux-dependent components in `Provider`.
- Wrap router-dependent components in the correct router harness:
- `MemoryRouter` for simple router hooks
- `createMemoryRouter` + `RouterProvider` when data-router behavior or `useBlocker` is involved
- Provide required app contexts such as page/detail/notification providers when components depend on them.
- Mock unrelated heavy subtrees when they are not part of the behavior under test.
- Treat these as known Jest risk areas and handle them with focused fixes:
- `import.meta.env`
- ESM-only dependencies
- asset imports
- RTK Query `fetchBaseQuery`
- timers and open handles
- Use `act(...)` for programmatic router navigation or other async state transitions when needed.
- Ensure select fields use valid empty values such as `''` rather than `undefined`.
- Avoid introducing runtime circular imports between Redux API modules, reducers, and store setup.
## Validation Expectations
Before finishing, Codex should run the narrowest useful checks for the task, and run broader checks when the scope justifies it.
Typical commands from the repository root:
- `npm run lint`
- `npm run tsc`
- `npm run test`
- `npm run lint:frontend`
- `npm run tsc:frontend`
If only a small area changed, targeted test runs are acceptable during iteration, but the final state should reflect the validation standard from the two policy files.
## Scope Control
- Implement only the requested task and directly necessary fixes.
- Do not add unrelated cleanup unless it is required to make the task correct or keep CI green.
- Do not add temporary test hacks without checking whether a production or harness-level fix is the better solution.
## Priority Order For Decisions
When tradeoffs appear, prefer:
1. Correctness
2. Keeping existing tests and CI stable
3. Narrow, local fixes
4. Consistency with existing repository patterns
5. Speed
## Output Expectations
- Be concise and practical.
- Mention files changed, validation performed, and any unresolved risk.
- If a task was only partially verifiable locally, say so clearly.
+12
View File
@@ -99,6 +99,14 @@ This section summarizes the overall architecture, structure, and technologies of
- Typical CI failures to avoid: unchecked Prettier drift, unused imports/variables (especially in tests), missing async return types or implicit `any`, and stale `eslint-disable` directives.
- Large fixtures or JSON assets (e.g., geodata) should remain excluded via `tsconfig.json`/`eslint.config.mjs` ignores; avoid importing them in type-checked code paths.
### Frontend Unit-Test Planning Guardrails
- When a feature touches shared frontend infrastructure such as `DetailView`, `EditableTable`, `DetailTabTable`, `UnsavedChangesProvider`, Redux API slices, or route-aware components, include explicit test-harness tasks in the plan.
- For each affected test, identify the required runtime context up front: `Provider` for Redux hooks, `MemoryRouter` or `createMemoryRouter` for router hooks, `PageContext` for detail/table helpers, and notification/dialog providers where hooks read context directly.
- Treat Vite-specific config (`import.meta.env`), ESM-only dependencies, and asset imports as Jest compatibility risks. Prefer narrow test-only shims or stable local abstractions over broad global remaps.
- If shared components pull in expensive or unrelated subtrees, plan to mock those subtrees in tests rather than weakening production code or adding wide Jest exceptions.
- Add a verification task for React Testing Library async behavior: wrap programmatic navigation or router state changes in `act(...)`, and assert against user-visible UI after async transitions settle.
- Add a teardown-check task whenever timers, notifications, RTK Query, or router transitions are involved, so the plan explicitly looks for open handles and console noise, not only red test failures.
---
# Codex Prompt for NOW Database Full-Stack Development
@@ -135,6 +143,7 @@ Implementation should cover all layers of the stack:
- **Routing & State Management:** Add routes with React Router and handle global state with Redux Toolkit or React context.
- **Auth & Permissions:** Use middleware to enforce role-based permissions. Hide or disable UI for unauthorized users.
- **Testing:** Use **Jest** + **@testing-library/react** for frontend tests, and **Mocha** + **supertest** for backend API tests. Add end-to-end coverage with **Cypress** if needed.
Frontend test planning must call out required providers, router mode, module mocks, and Jest/Vite compatibility for each changed area.
- **Documentation & Deployment:** Update `.env` templates, Docker Compose, and internal documentation if configuration changes are needed.
---
@@ -182,6 +191,7 @@ Provide a **machine-readable JSON array** of granular tasks like:
- **Error Handling:** Ensure API returns structured errors. Show clear messages in UI.
- **Security:** Use parameterized queries (via Prisma) and sanitize user inputs.
- **Rollback:** Feature-flag critical changes for safe deployment.
- **Test Regressions:** Avoid broad Jest config changes that can alter unrelated suites. Prefer the smallest production fix or the narrowest test-specific shim that resolves the real incompatibility.
---
@@ -197,6 +207,8 @@ Provide a **machine-readable JSON array** of granular tasks like:
- [ ] All acceptance criteria met
- [ ] Unit, integration, and E2E tests pass
- [ ] Code passes linting and type checks
- [ ] Frontend tests include the required providers/router/context and do not rely on missing app runtime state
- [ ] Jest compatibility issues (`import.meta.env`, ESM packages, assets, RTK Query/fetch, timers) are handled with narrow fixes
- [ ] Database migrations are applied and reversible
- [ ] Role-based permissions verified
- [ ] Documentation and changelog updated
@@ -64,6 +64,15 @@ Implement **exactly one task** from an approved feature plan.
- Common failure patterns to avoid: missing Prettier formatting, unused imports/variables in tests, missing async return types or implicit `any`, and stale `eslint-disable` directives.
- Keep large fixtures/geojson assets out of type-checked paths; rely on `tsconfig`/ESLint ignores already defined (see `frontend/tsconfig.json`, `backend/tsconfig.json`, and `eslint.config.mjs`).
### Frontend unit-test checklist (mandatory when frontend code or frontend tests change)
- Before changing Jest config, first check whether the failure is really caused by missing test runtime context. Components using Redux hooks must render inside `<Provider>`. Components using `useNavigate`, `useLocation`, `useBlocker`, or route loaders must render inside the correct router (`MemoryRouter` vs `createMemoryRouter` + `RouterProvider`).
- If a component depends on app-specific contexts such as page/detail/notification providers, supply those providers in the test harness or mock the smallest unrelated subtree that requires them.
- Prefer narrow fixes over global Jest hacks. Do not broadly remap application modules unless the task explicitly requires it. For `import.meta.env`, ESM-only libraries, assets, or browser APIs, use a dedicated Jest tsconfig, focused moduleNameMapper entries, or a small test stub.
- When shared UI pulls in unrelated heavy subtrees, mock those subtrees in the test to keep the assertion focused. Do not weaken production behavior just to satisfy a unit test unless the production dependency is itself accidental.
- For RTK Query or `fetchBaseQuery`, ensure the Jest environment provides `fetch`, `Request`, `Response`, and any methods the library expects such as `clone()`.
- For selects and MUI form controls, ensure test defaults are valid values (`''` instead of `undefined` for empty select state) so tests do not hide warnings that would fail CI logs later.
- Wrap programmatic router transitions and similar async state changes in `act(...)`, and verify that timers, notifications, and async navigation do not leave open handles.
### Quality / Style
- Follow ESLint + Prettier + TypeScript strict.
- Typed interfaces / DTOs for all API payloads.
@@ -83,6 +92,7 @@ Implement **exactly one task** from an approved feature plan.
- Follow atomic layout (`components/`, `pages/`, `redux/`, `hooks/`).
- Integrate with Redux slices for data fetching (Axios or fetch via async thunks).
- Ensure ARIA labels, keyboard navigation, and responsive design.
- Avoid introducing new runtime circular dependencies between Redux slices, API modules, and store setup. Prefer `import type` for type-only dependencies and keep API modules free of store/reducer runtime imports when possible.
**Database**
- Schema changes via Prisma migrations (`prisma migrate dev`).
@@ -99,6 +109,8 @@ Implement **exactly one task** from an approved feature plan.
- Aim for > 80 % coverage for changed modules.
- Backend tests mock Prisma or use test DB.
- Frontend tests mock API calls and simulate user flows.
- Frontend test updates must verify the real render path is reachable before asserting controls; if a shared component stays in loading/error state, fix the harness rather than forcing the assertion.
- If Jest config is modified, confirm the change does not break unrelated suites by changing module resolution, transform mode, or global mocks.
**Docs / CI**
- Update `.env.template`, README sections, and API docs when specified.
@@ -212,6 +224,7 @@ JWT_SECRET="replace_me"
- Change unrelated files.
- Add new packages unless listed in `packages`.
- Bypass lint / type rules or CI checks.
- Add broad temporary Jest workarounds such as global module remaps, disabled caches, or wide transform exceptions unless you also verify they are truly necessary and safe for unrelated suites.
---
@@ -219,6 +232,8 @@ JWT_SECRET="replace_me"
- All acceptance criteria met.
- TypeScript compiles without errors.
- Backend & frontend tests pass.
- Frontend tests have the correct Provider/router/context wrappers, and async router actions are wrapped in `act(...)` where needed.
- Jest/browser shims are minimal and compatible with Vite config, ESM dependencies, RTK Query, and asset imports used by the changed code.
- Prisma migrations exist if `migrations:true`.
- Role-based permissions verified.
- Docs and `.env.template` updated if required.