🔧 Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 2
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
MSW is a tool that allows you to intercept API calls and modify their responses. This helps you test your app in more realistic scenarios, with different responses.
From a high-level view, MSW lets us intercept API calls in two scenarios:
- In the browser: This allows you to mock API responses while you're developing the app, making it easier to test different responses as you write your code.
- In a Node.js environment: This is typically the case when running tests, such as with Vitest.
In this section, we'll configure MSW for the second scenario, to mock API calls in a Node.js environment during testing.
1. Step 1
Install MSW as a development dependency and initialize it:
npm install msw --save-dev
npx msw init ./public
- Setup Mock Server
Next, under you /tests/mock folder create a mock server that runs in a Node environment for use in your tests:
5. Update the Test Setup
In your setup file (pointed to in your vite.config.ts
), configure the mock server to start and stop during the testing lifecycle:
This configuration ensures that MSW is properly set up, cleaned up after each test, and the handlers are reset to maintain test isolation.
4. Setting up Handlers
Next, under your /tests/mocks folder setup your handlers. MSW provides handlers for different HTTP methods, like GET
, POST
, etc. Here's how you can mock the GET
request for our API:
and then you set those handlers in your server:
6. Writing Tests
Here’s how you can write tests that use the mocked server and handlers. In ItemList.test.tsx:
Check out that to query the list container I set a data-testid="list"
in the container element of that component.
In this example:
- We mock the API's
GET
response using MSW. - We handle both successful and failed API requests.
- We test that the UI displays the correct information or error message based on the response.
Let me know if you need any further improvements or explanations!
...