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 HTTP with MSW instead of stubbing global fetch
Use request interception (MSW) so tests verify the real endpoint/method, not a blanket fetch stub.
Bad example
| 1 | function mockFetch(response: Response) { |
| 2 | vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response)); |
| 3 | } |
| 4 |
|
| 5 | it('loads following', async () => { |
| 6 | mockFetch(new Response(JSON.stringify({ person: [1] }))); |
| 7 | await getFollowing(); |
| 8 | }); |
Explanation (EN)
A blanket fetch stub returns the same response for any URL, so the test can't tell whether the code called the right endpoint with the right method.
Objašnjenje (HR)
Globalni stub fetch-a vraca isti odgovor za bilo koji URL, pa test ne moze utvrditi je li kod pozvao pravi endpoint pravom metodom.
Good example
| 1 | const worker = setupWorker( |
| 2 | http.get('/api/user/following', () => HttpResponse.json({ person: [1] })), |
| 3 | ); |
| 4 |
|
| 5 | it('loads following', async () => { |
| 6 | await getFollowing(); |
| 7 | // MSW only matches GET /api/user/following; a wrong URL/method 404s. |
| 8 | }); |
Explanation (EN)
MSW matches per method+path, so an unexpected call fails the request, giving you confidence the code hit the intended endpoint.
Objašnjenje (HR)
MSW poklapa po metodi+putanji, pa neocekivani poziv pada, sto daje sigurnost da je kod pogodio zeljeni endpoint.