RFC: Built-in support for HTTP mocking
See original GitHub issueThere’s often a need to mock network calls when writing unit tests. While one can use jest.mock
to implement the http API of your choice - or use modules like jest-fetch-mock
that only works for fetch
- this is often technical debt the moment you swap out your HTTP abstraction. If one migrates to request
or axios
, they often have to also switch out their mock implementation. This pain is potentially even worse if moving from e.g. traditional xhr
requests to fetch
, or vice versa. Or even starting to use GraphQL instead of the more traditional REST based approaches.
One could set up a mock server with some canned responses (e.g. create-test-server
is nice), but that is often slower than you want it to be, especially for unit tests which needs to run against a clean instance every single test.
A third alternative, and what I want to see in Jest, is to mock out the http layer of the runtime. nock
is a module which does this for node (so works fine also for JSDom based tests), but I find its API clunky to use and work with. Other alternatives are sinon
or faux-jax
.
If we could provide a simpler and/or more intuitive API out of the box with Jest, I think that might solve a lot of common issues where people today find solutions to plug into Jest.
I don’t have any particular API suggestions here, but I think something akin to jest.useFakeTimers()
(say jest.useFakeNetwork()
) with related APIs such as jest.fakeGet('url', {headers}, body)
might be a good start. Looking at existing solutions for inspirations sounds like a great way forward! Having something for GraphQL out of the box would be awesome as well.
One source of inspiration beyond sinon
and faux-jax
could be ava-nock
. Especially the NOCK_MODE
feature sounds like an awesome watch plugin for jest.
Done! 10 days isn’t too bad 😄
Issue Analytics
- State:
- Created 5 years ago
- Reactions:46
- Comments:11 (2 by maintainers)
Top GitHub Comments
@SimenB yeah we have this (something similar) at Spotify and our intention is to open source it this quarter. Happy to hop on video chat sometime and show you how it works.
+1 Love to see what you’re working on @SimenB