Rules Hub
Coding Rules Library
Inject fresh dependencies in test utilities
Always create fresh instances of stateful dependencies (like QueryClient or Stores) inside test helpers to ensure test isolation.
Bad example
| 1 | import { queryClient } from '@/app/query-client'; // Global singleton |
| 2 | import { render } from '@testing-library/react'; |
| 3 |
|
| 4 | export function renderWithContext(ui: React.ReactNode) { |
| 5 | // Bad: Reusing the global client means state leaks between tests |
| 6 | return render( |
| 7 | <QueryClientProvider client={queryClient}> |
| 8 | {ui} |
| 9 | </QueryClientProvider> |
| 10 | ); |
| 11 | } |
Explanation (EN)
Using a global singleton in test helpers causes state (like cache) to persist between tests. This leads to flaky tests where the outcome depends on the execution order of previous tests.
Objašnjenje (HR)
Korištenje globalnog singletona u testnim pomoćnim funkcijama uzrokuje zadržavanje stanja (poput cachea) između testova. To dovodi do nepouzdanih testova čiji ishod ovisi o redoslijedu izvršavanja prethodnih testova.
Good example
| 1 | import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; |
| 2 | import { render } from '@testing-library/react'; |
| 3 |
|
| 4 | export function renderWithContext(ui: React.ReactNode) { |
| 5 | // Good: A fresh client is created for every test render |
| 6 | const testClient = new QueryClient({ |
| 7 | defaultOptions: { queries: { retry: false } }, |
| 8 | }); |
| 9 |
|
| 10 | return render( |
| 11 | <QueryClientProvider client={testClient}> |
| 12 | {ui} |
| 13 | </QueryClientProvider> |
| 14 | ); |
| 15 | } |
Explanation (EN)
Creating a new instance of the dependency (e.g., QueryClient) inside the test helper guarantees that every test starts with a clean slate, ensuring complete isolation and deterministic results.
Objašnjenje (HR)
Kreiranje nove instance ovisnosti (npr. QueryClient) unutar testne pomoćne funkcije jamči da svaki test započinje s čistim stanjem, osiguravajući potpunu izolaciju i determinističke rezultate.
Notes (EN)
This applies to any stateful dependency injected via Context, such as Redux stores, Apollo clients, or React Router contexts.
Bilješke (HR)
Ovo se odnosi na bilo koju ovisnost sa stanjem koja se ubacuje putem Contexta, kao što su Redux store-ovi, Apollo klijenti ili React Router konteksti.