Mock the network; with mock service workers.

Adam Donaghy
1 min readMar 8, 2021

--

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)

From MSW docs

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

  1. 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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Adam Donaghy
Adam Donaghy

No responses yet

Write a response