iTranslated by AI
Automated Testing for React + Vite with Playwright and MSW
I tried out the following configuration.
Environment
- react 18.0.0
- react-dom 18.0.0
- react-router-dom 6.3.0
- typescript 4.6.3
- msw 0.42.3
- vite 2.9.9
Setup
Project Creation
Create a project using vite init.
npm create vite@latest react-vite-playwright-msw-sample -- --template react-ts
Go into the created project and install additional dependencies.
cd react-vite-playwright-msw-sample
npm i react-router-dom
npm i -D @playwright/test msw
npx playwright install
Preparing a Sample User Registration Form
Since we need a UI to test, let's prepare a sample user registration form.
import { FC, useState } from 'react'
import { useNavigate } from 'react-router-dom'
export const RegisterUser: FC = () => {
const navigate = useNavigate()
const [email, setEmail] = useState('')
const [name, setName] = useState('')
return (
<form
onSubmit={(e) => {
e.preventDefault()
;(async () => {
// Call API and save user information
await fetch('http://localhost:8000/api/users', {
method: 'POST',
body: JSON.stringify({
email,
name,
}),
headers: {
'Content-Type': 'application/json',
},
})
// Transition to my page
navigate('/my-page')
})()
}}
>
<input
type="email"
name="email"
onChange={(e) => setEmail(e.target.value)}
data-test="emailInput"
/>
<input
type="name"
name="name"
onChange={(e) => setName(e.target.value)}
data-test="nameInput"
/>
<button type="submit" data-test="submitButton">
Submit
</button>
</form>
)
}
It is assumed that you can register a user by hitting the API at http://localhost:8000/api/users with a POST request. The API will be mocked with msw later.
Let's also prepare the my page where the user is expected to be redirected after registration.
import { FC } from 'react'
export const MyPage: FC = () => {
return (
<div data-test="myPagePage">
<h1>My Page</h1>
</div>
)
}
Also, set up routing using react-router.
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
import { RegisterUser } from './register-user'
import { Registered } from './registered'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/register-user" element={<RegisterUser />} />
<Route path="/my-page" element={<MyPage />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
)
npm run dev
You can see the form by running the above and opening http://localhost:3000/register-user in your browser.
Setting Up Playwright
Create a Playwright configuration file. The settings will vary depending on preferences and situations, but let's proceed with the following for now.
import { devices, PlaywrightTestConfig } from '@playwright/test'
const config: PlaywrightTestConfig = {
// Run tests in parallel as much as possible
fullyParallel: true,
// Perform multi-browser testing
projects: [
{
name: 'Pixel 4',
use: {
browserName: 'chromium',
...devices['Pixel 4'],
},
},
{
name: 'iPhone 11',
use: {
browserName: 'webkit',
...devices['iPhone 11'],
},
},
],
}
export default config
Setting Up MSW
Set up MSW. First, run the following init command to create public/mockServiceWorker.js. You don't need to touch this file.
npx msw init public
Then, I prepared the following initialization function for MSW mocking. It generates an MSW worker that mocks http://localhost:8000/api/users.
import { setupWorker, rest, SetupWorkerApi } from 'msw'
export const buildMswWorker = (): SetupWorkerApi => {
const worker = setupWorker(
rest.post('http://localhost:8000/api/users', (_req, res, ctx) => {
return res(
ctx.json({
message: 'Success.',
})
)
})
)
return worker
}
Make it load in main.tsx. We have prepared VITE_MOCKED_API as a VITE environment variable, and when it is set to 'true', the MSW mock will be enabled. Also, by using dynamic import, we ensure that MSW is not included in the bundle when it is not in use.
+;(async () => {
+ if (import.meta.env.VITE_MOCKED_API === 'true') {
+ const { buildMswWorker } = await import('./testing-util/msw-util')
+ const worker = buildMswWorker()
+ await worker.start()
+ }
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/" element={<Form />} />
<Route path="/registered" element={<Registered />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
)
+})()
To start with MSW enabled, run the following command:
VITE_MOCKED_API=true npm run dev
It's working if you see the following in the browser's DevTools console:
[MSW] Mocking enabled.
Writing Tests
Write the following test and run it while the development server with MSW enabled is running.
import { expect, test } from '@playwright/test'
test('register a user', async ({ page }) => {
// Open the registration page
await page.goto('http://localhost:3000/register-user')
// Fill in the form input fields
await page.fill('[data-test=emailInput]', 'foo@example.com')
await page.fill('[data-test=nameInput]', 'foo')
// Press the form submit button
await page.click('[data-test=submitButton]')
// Confirm transition to my page
await expect(page.locator('[data-test=myPagePage]')).toHaveCount(1)
})
You can run the tests with the following command:
npx playwright test
The command above runs in headless browser mode. If you want to check the tests while observing the browser, add the --headed option. In that case, it will be easier to check by running a single worker rather than parallel execution. Also, add --workers 1.
npx playwright test --headed --workers 1
There may be times when a test doesn't work as intended and you want to debug it. In such cases, await page.pause() is useful.
test('register a user', async ({ page }) => {
// Open the registration page
await page.goto('http://localhost:3000/register-user')
+ // Stop here
+ await page.pause()
Also, if you want to run only a specific test, you can use test.only.
-test('register a user', async ({ page }) => {
+test.only('register a user', async ({ page }) => {
// Open the registration page
await page.goto('http://localhost:3000/register-user')
References
- Getting Started | Vite
- mizchi is using Twitter: "For writing e2e, playwrgiht/test e2e is so excellent that 30 cross-browser tests finish in 6 seconds" / Twitter
- Small techniques around webpack that reduced Nuxt.js bundle size by 55% - Qiita
- mswjs/msw: Seamless REST/GraphQL API mocking library for browser and Node.js.
- Front-end development accelerated by MSW
Discussion