Mock Service Worker
Mock Service Worker
MSW Setup
- Create a test file
- Understand query and return values (use Chrome Fetch/XHR to analyse)
- Create a MSW handler (api url, query params and create return json)
- Setup beforeAll, afterEach and afterAll hooks in the test file
- In a test render component and wait for it to be visible
- Write assertions to verify expectations
With NX
Within a NX project.
- Create Storybook library
- Install MSW
- Create public folder then run msw init
- Create MSW Mock Handlers
- Configure Mock MSW browser worker to run Handers
- Configure Storybook preview to starter MSW browser worker
- Add Public directory to NX workspace.json
Create a React component that have API endpoints configured in the MSW Handers.
When running Should get the mocked response.
npx nx storybook shared-ui
Step 7: Configure NX Workspace
"storybook": {
"executor": "@nrwl/storybook:storybook",
"options": {
"uiFramework": "@storybook/react",
"port": 4400,
"config": {
"configFolder": "libs/shared/ui/.storybook"
},
"staticDir": ["public"] // Add public folder to workspace.json
},
"configurations": {
"ci": {
"quiet": true
}
}
},
Links
- Mock Service Worker
- Configure MSW in NX
- Example with Next.js
- Example with Storybook
- Mocking APIs with Storybook and NX
Questions
Which engineering decision related to this topic has the highest switching cost once made — and how do you make it well with incomplete information?
- At what scale or complexity level does the right answer to this topic change significantly?
- How does the introduction of AI-native workflows change the conventional wisdom about this technology?
- Which anti-pattern in this area is most commonly introduced by developers who know enough to be dangerous but not enough to know what they don't know?