Mock the network; with mock service workers.
While I’ve been developing recently it’s always been nice to mock the network rather than the service that hits the network. It’s a small but significant change that let me mock almost nothing, and drastically increases my confidence in my work. (full example on my github)
This came in handy recently when working on a graphql server which was collating a selection of microservices, where each resolver could look at different microservice. Mocking each microservice’s response made mocking the resolvers easy. This was really easy by using Mock Service Worker.
To get this working all I had to do was
- Setup the default handlers
2. Describe how tests will be mocked in tests
3. Enable mocking in tests
4. Write the test
5. Profit. For each new url that needs to be hit, we can mock up a response. And if we need to, we can mock a different response. The full example can be found on my github and it can work with any url library.