Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Don't manually restore mocks when the test runner auto-restores them
If the test config enables automatic mock restoration, drop manual mockRestore() calls and the try/finally that exists only to run them.
Bad example
| 1 | const spy = vi.spyOn(obj, 'method').mockImplementation(() => 1); |
| 2 |
|
| 3 | try { |
| 4 | render(<Component />); |
| 5 | expect(spy).toHaveBeenCalled(); |
| 6 | } finally { |
| 7 | spy.mockRestore(); |
| 8 | } |
Explanation (EN)
The try/finally exists only to restore the spy, but the runner already restores mocks automatically between tests, so this is dead ceremony that obscures the actual assertion.
Objašnjenje (HR)
try/finally postoji samo da vrati spy u prvotno stanje, ali runner vec automatski resetira mockove izmedu testova, pa je ovo nepotrebna ceremonija koja zamagljuje stvarnu tvrdnju.
Good example
| 1 | // vitest.config: test: { restoreMocks: true } |
| 2 | const spy = vi.spyOn(obj, 'method').mockImplementation(() => 1); |
| 3 |
|
| 4 | render(<Component />); |
| 5 | expect(spy).toHaveBeenCalled(); |
| 6 | // no manual restore: runner restores automatically |
Explanation (EN)
With auto-restoration configured, the spy is reset after the test runs, so the test stays flat and focused on what it actually verifies.
Objašnjenje (HR)
Uz konfiguriran automatski reset, spy se vraca u prvotno stanje nakon testa, pa test ostaje plosnat i fokusiran na ono sto stvarno provjerava.
Exceptions / Tradeoffs (EN)
If you need to restore a spy mid-test (before the test ends) so later code sees the real implementation, an explicit restore is still warranted.
Iznimke / Tradeoffi (HR)
Ako spy trebas vratiti usred testa (prije nego test zavrsi) kako bi kasniji kod vidio pravu implementaciju, eksplicitni restore je i dalje opravdan.