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
}
}
},