Song Turbo Developer Certification - Foundations
Part 6: Mocking APIs with MSW
Sometimes in our project it is a good idea not to have to hit the external API for data. Reasons could be:
- The API is not ready yet
- You work where you dont have a good internet connection
- Hitting the API comes with a cost
For these scenarios we use a framework called MSW - Mock Service Worker. Having it active in our project means it will intercept all network requests. It will examine and see if this is a request to an API that we want to mock and if that is the case, it will instead return some mocked data.
Mocking is turned on using .env environment flag NEXT_PUBLIC_API_MOCKING_ENABLED in the web app and also on a per API level in @turbo-blog/api-mocks package
Concepts to be grasped
- Mocking with MSW
Reading material
Tasks
1. Setup turbo-posts-api-mocks addon
- Create a new addon package
@turbo-blog/turbo-posts-api-mocksinpackages/addonsdirectory. - You can copy the
example-api-mocksand see how it is constructed and make the correct changes - Use the data from references and copy that over to the mocking addon. Return that data when a request to the api is made.
- To mock a request with query parameters (like the post id) check the MSW docs.
2. Connect it to the main api mocks
- Import the addon in the
@turbo-blog/api-mockspackage - Connect to the handlers in the file
handlers.tsin@turbo-blog/api-mockspackage - Create a new flag for turning the api mocks on or off
MSW intercept network requests, what are other ways to mock data?
What is the main advantage of using MSW?
Evaluation
To verify that mocking occurs, in the terminal, run the following command:
yarn dev:webThe server should start and you should be able to access the production application at localhost:3000 (opens in a new tab) in your browser.
Open the browser devtools and the Console panel. Check to see that MSW is active and is intercepting the calls to the API.
Experiment with turning mocking on and off using the various flags. Changes to .env files requires a server restart.