Reputation: 50770
I am trying to use MSW for running my React app with mock data. Below is my index.js;
import React from 'react';
import * as serviceWorker from './serviceWorker';
if (process.env.NODE_ENV === 'development') {
const { worker } = require('./mocks/browser')
worker.start().then(() => renderApp())
}
My service worker JS is located at public/mockServiceWorker.js
My src/mocks/browser.js is as below;
import { setupWorker } from 'msw'
import { handlers } from './handlers'
// This configures a Service Worker with the given request handlers.
export const worker = setupWorker(...handlers)
Also my src/mocks/index.js is as below;
if (typeof window === "undefined") {
const { server } = require("mocks/server");
server.listen();
} else {
const { worker } = require("mocks/browser");
worker.start();
}
Now when running the app in browser, I see the following error;
Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/mockServiceWorker.js'): The script has an unsupported MIME type ('text/html').
Also I am a bit confused as I am seeing an additional serviceWorker.js created under src (this seems to be generated via create-react-app) and as you can see above, this is also imported in src/index.js (again via create-react-app) , but the one I am looking to use is at public/mockServiceWorker.js
I am not sure if those are unrelated. I am trying to follow the example at https://github.com/ghoshnirmalya/introduction-to-msw
Also MSW official page for reference - https://mswjs.io/docs/getting-started/integrate/browser
Upvotes: 1
Views: 12763
Reputation: 11
The issue is most probably that your application doesn't see the serviceWorker.js
in public
folder. So it fails to register.
You probably, have to copy the worker script via the msw
CLI utility. I had to run npx msw init <PUBLIC_DIR>
, in my example, it was npx msw init ./public
.
Upvotes: 1
Reputation: 7391
I am assuming that you are using Create React App (CRA). The MSW documentation says that you should remove the line below from the src/index.js
file:
serviceWorker.unregister()
Did you do this?
The CRA template already comes with a service worker, this is why you have two files.
The CRA service worker is disabled by default (hence the serviceWorker.unregister()
line). By removing the unregister
line, you will be running the default service worker on production. Make sure that this is what you want.
Upvotes: 0