简体   繁体   中英

How to initialise mock service worker (msw) with reactjs project

I tried using msw for local dev and testing using official guide

but faced following issue:

[MSW] Failed to register a Service Worker for scope ('http://localhost:8080/') with script ('http://localhost:8080/mockServiceWorker.js'): Service Worker script does not exist at the given path.

Did you forget to run "npx msw init <PUBLIC_DIR>"?

Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init


  [1]: https://mswjs.io/docs/getting-started/integrate/browser

My folder structure:

在此处输入图像描述

As the error message suggests, you haven't placed the Service Worker ( mockServiceWorker.js ) script in your public directory. Based on your screenshot, your public directory is most likely ./build .

Execute this command to place the worker script in your public directory:

$ npx msw init ./build

You should be able to access the worker script in your running application by this URL: http://localhost:8080/mockServiceWorker.js . That should return the contents of the mockServiceWorker.js file to be registered in your app.

You need to run the command using your public folder, not build. Your public folder is the one that has the contents copied to your build folder. If you place the file on your build folder, it will not go to your source control (if you are correctly not commiting build files).

Instructions compatible with create-react-app:

After running the command

$ npx msw init ./public

you need to run yarn build and then you can use storybook. Also don' t forget to run storybook with access to the public folder:

"storybook": "start-storybook -s ./public"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM