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).
Mock process.exit in tests instead of mutating process.exitCode
Intercept exit via an explicit spy that throws; don't read/reassign the real process.exitCode, which can clash with the test runner.
Bad example
| 1 | const before = process.exitCode; |
| 2 | process.exitCode = 0; |
| 3 | await runScript(['dev']); |
| 4 | expect(process.exitCode).toBe(1); |
| 5 | process.exitCode = before; |
Explanation (EN)
Mutating the real process.exitCode bleeds into the runner's own exit handling and the manual save/restore is fragile and easy to leak across tests.
Objašnjenje (HR)
Mijenjanje stvarnog process.exitCode prelijeva se u runnerovo upravljanje izlazom, a rucno spremanje/vracanje je krhko i lako iscuri izmedu testova.
Good example
| 1 | function stubExit() { |
| 2 | return vi.spyOn(process, 'exit').mockImplementation(code => { |
| 3 | throw new Error(`process.exit:${code ?? 0}`); |
| 4 | }); |
| 5 | } |
| 6 |
|
| 7 | test('exits with code 1 on failure', async () => { |
| 8 | stubExit(); |
| 9 | await expect(runScript(['dev'])).rejects.toThrow('process.exit:1'); |
| 10 | }); |
Explanation (EN)
An explicit spy that throws keeps the side effect inside the mock, never touches real process state, and makes the intercepted exit code directly assertable.
Objašnjenje (HR)
Eksplicitni spy koji baca drzi nuspojavu unutar mocka, nikad ne dira stvarno stanje procesa i cini presretnuti izlazni kod izravno provjerljivim.