3 ms·
Mocking a global function in that manner is a poor solution. Two better options: 1. If you are testing that the proper Request is built from your config, and
by jonahx 4y ago
Mocking a global function in that manner is a poor solution.
Two better options:
1. If you are testing that the proper Request is built from your config, and that's hairy logic you want to test, pull that logic out as as a pure function (config => Request) and test that.
2. If you really want to test "through" the current function, explicitly make the fetch function one of its dependencies, passed in as an argument, with a default value of "window.fetch" which is used in production. Now you can keep your current approach but what you are doing is explicit, and requires no global object overrides for your tests.
- bern4444 4y agoMocking a global function in a single test is not a poor solution. To your first suggestion, that requires making a private function public which I dislike. The 2nd suggestion of using dependency injection does make testing easier, but injecting the same dependency over and over in a codebase (IE, anywhere that makes an HTTP request) is bad ergonomics. Mocking the global function (or standing up a test server via MSW) is the best solution to not get blocked, validate your code, and avoiding making src code changes to solely to accommodate tests.
- jonahx 4y agoIt is a very poor solution because you are coupling your tests to private implementation detail of the function you are testing. > but injecting the same dependency over and over in a codebase (IE, anywhere that makes an HTTP request) is bad ergonomics. The production dep is the default one, as I noted, so it gets injected automatically without the calling code needing to even know about it. This has the benefit of explicitly documenting in the signature all your functions dependencies with side effects. This alone would make it worth it, even ignoring the benefits on your test code. > to not get blocked "not betting blocked" isn't a justification for bad approaches. In any case, what I am suggesting will be just as fast. > and avoiding making src code changes to solely to accommodate tests. You won't be. The only src code change you'd be making is to the function signature to explicitly document its dependencies, which you should have done from the beginning. I will argue that having global, side effectful dependencies scattered across your code base is one of the worst errors you can make.