Andrew's Digital Garden

Don't mock fetch (or any other system functions)

tl;dr - when possible, avoid mocking fetch. In fact, avoid mocking anything you don't own (when possible)

Mocking a system function is strange - you want to test against that system function. You're not gonna mock Document.createElement, because then you're not testing that your code works with the system - you're testing it works with the mock.

For something like fetch, using msw is a better alternative. This way you're still testing as much of your code as you can, without having to orchestrate servers, backends, etc. You still call fetch, and you still have a real-ish server that responds as it would in production.

If you have to mock something, at least mock it in a central location to remove duplication and avoid having to re-implement a slightly different variation everywhere. Ideally, move it as far away from a mock as you can.

https://kentcdodds.com/blog/stop-mocking-fetch

[[20201223160329-mocks-vs-stubs]]

[[mocking]] [[testing]]

Don't mock fetch (or any other system functions)