Skip to main content

Mock Service Worker

Mock Service Worker

MSW Setup

  1. Create a test file
  2. Understand query and return values (use Chrome Fetch/XHR to analyse)
  3. Create a MSW handler (api url, query params and create return json)
  4. Setup beforeAll, afterEach and afterAll hooks in the test file
  5. In a test render component and wait for it to be visible
  6. Write assertions to verify expectations

Udemy course

With NX

Within a NX project.

  1. Create Storybook library
  2. Install MSW
  3. Create public folder then run msw init
  4. Create MSW Mock Handlers
  5. Configure Mock MSW browser worker to run Handers
  6. Configure Storybook preview to starter MSW browser worker
  7. 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
}
}
},