I have tried to get working mock service worker inside a react vite PWA project. I have setup a mock service worker by following their documentation. I have setup handlers like this:
import { rest } from 'msw'
export const handlers = [
rest.post('/login', (req, res, ctx) => {
// Persist user's authentication in the session
console.log('req', req)
sessionStorage.setItem('is-authenticated', 'true')
return res(
// Respond with a 200 status code
ctx.status(200),
)
}),
rest.get('/user', (_, res, ctx) => {
// Check if the user is authenticated in this session
const isAuthenticated = sessionStorage.getItem('is-authenticated')
if (!isAuthenticated) {
// If not authenticated, respond with a 403 error
return res(
ctx.status(403),
ctx.json({
errorMessage: 'Not authorized',
}),
)
}
// If authenticated, return a mocked user details
return res(
ctx.status(200),
ctx.json({
username: 'admin',
}),
)
}),
]
I am setuping and starting worker like this:
async function main() {
console.log(process.env.NODE_ENV)
if (process.env.NODE_ENV === 'development') {
await worker.start({ onUnhandledRequest: 'warn' })
worker.printHandlers()
}
const queryClient = new QueryClient()
const router = createBrowserRouter([
{
path: '/',
element: <SignIn />,
},
{
path: '/dashboard',
element: <div>Hello dashboard here!</div>,
},
])
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</React.StrictMode>,
)
}
I can see that msw
is enabled in the browser. I can see that file is available at http://localhost:5173/mockServiceWorker.js
. Also handlers are printed in the console:
{
"shouldSkip": false,
"ctx": {},
"info": {
"header": "POST /login",
"path": "/login",
"method": "POST",
"callFrame": "http://localhost:5173/node_modules/.vite/deps/msw.js?v=3f9ea0d4:24895:40"
}
}
But, when I am making a request from my app, like this for example:
const mutation = useMutation({
mutationFn: (data: FormData) => {
console.log('data', data)
return axios.post('/login', data)
},
onSuccess: () => navigate('/dashboard'),
})
I can see that nothing is intercepted from the msw
.
I have tried to create a codesanbox, but I couldn't get it working there. At least you can see how the files are looking and what kind of setup I have. How should I debug this, I have tried what there is suggested at msw documentation site, but with no luck?
How can I get msw
fixed so that it intercepts requests?
I see that the file registerSW.js
in the dev-dist
directory is doing something that is obstructing the registration of mockServiceWorker.js
. The code in registerSW.js
looks like this:
if('serviceWorker' in navigator) navigator.serviceWorker.register('/dev-sw.js?dev-sw', { scope: '/', type: 'classic' })
I see in browser Application tab that only dev-sw.js
is registered as service worker. If I comment out that piece of code, mockServiceWorker
gets registered.How can I register both service workers and not just one?
It looks like your app already has a Service Worker. I believe you can only register 1 Service Worker per host. This may be why the
mockServiceWorker.js
fails to register, resulting in no request being intercepted.To fix this, you can combine worker scripts using the
importScripts
standard API.Perhaps raising this in the Vite community can give you a more appropriate answer as to the best way to combine the workers.