Seamless REST/GraphQL API mocking library for browser and Node.
MSW seems to gain some popularity fast, and most of it is coming from the React community.
It even became the recommended approach to mock HTTP requests with React Testing Library.
Kent C. Dodds wrote a blog post "Stop mocking fetch" in which he explains what problems MSW can resolve. If you're not familiar with MSW, I would suggest skimming through the documentation or to read Kent's blog before continuing.
Because it receives a lot of positive feedback I wanted to give this a shot with Angular.
In this post, we'll create a proof of concept to search a GitHub user for a username.
The implementation of the Angular service, looks as this:
The first step is to install MSW with the following command.
This will create the ./src/mockServiceWorker.js file which includes the Service Worker.
npxmswinitsrc
To be able to serve the service worker, add it to the assets inside the angular.json file.
With this step, the mockServiceWorker.js file will be copied over to the build output.
Just like when the application is served, the mock server needs to be imported to register the service worker.
We import the mocks in the ./src/test.ts file where the test environment is created, so it's available for all tests.
./src/test.ts
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing'
import {getTestBed} from '@angular/core/testing'
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing'
import './mocks/browser'
declareconstrequire:{
context(
path:string,
deep?:boolean,
filter?:RegExp,
):{
keys():string[]
<T>(id:string):T
}
}
// First, initialize the Angular testing environment.
While Angular already provides a way to mock our services via its dependency injection, I think we can still benefit from MSW in an Angular project.
It doesn't just help to mock services during tests, but as the example setup shows, it can also be used during the development cycle. Especially, when multiple teams (frontend and backend) are working on the same application or when the backend isn't ready yet.
MSW also provides a way to share a server across multiple layers of the testing pyramid. The server can be used during unit tests, integration tests, and end-to-end tests. This can help with the maintenance of your tests.