DEV Community

Cover image for Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 2
Juan de Tomaso
Juan de Tomaso

Posted on

Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 2

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:

  1. 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.
  2. 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
Enter fullscreen mode Exit fullscreen mode
  1. Setup Mock Server

Next, under you /tests/mock folder create a mock server that runs in a Node environment for use in your tests:

mock server

5. Update the Test Setup

In your test setup file, configure the mock server to start and stop during the testing lifecycle:

setup server cycles

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:

handlers file

and then you set those handlers in your server:

mock server updated

6. Writing Tests

Here’s how you can write tests that use the mocked server and handlers. In ItemList.test.tsx:

test file

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!

Top comments (0)