Languages & Frameworks

Mock Service Worker

Published: Oct 28, 2020
Oct 2020

Web applications, especially those written for internal use in enterprises, are usually written in two parts. The user interface and some business logic run in the web browser while business logic, authorization and persistence run on a server. These two halves normally communicate via JSON over HTTP. The endpoints shouldn't be mistaken for a real API; they're simply an implementation detail of an application that is split across two run-time environments. At the same time, they provide a valid seam to test the pieces individually. When testing the JavaScript part, the server side can be stubbed and mocked at the network level by a tool such as Mountebank. An alternative approach is to intercept the requests in the browser. We like the approach taken by Mock Service Worker because with service workers it uses an abstraction familiar to developers. This approach results in a simpler setup and faster test execution. However, because these tests don't test the actual network layer, you want to implement some end-to-end tests as part of a healthy test pyramid.