I have a small setup with webpack module federation, one container app and one remote. The remote is exposing itself completely and the container is consuming it to show it after clicking a navigation link like /users.
The container is reachable at localhost:8080, the remote at localhost:3001
Now, the remote is using mockup service worker (https://mswjs.io/), which works fine when visiting the app directly. When called through the container, an error comes up:
Uncaught (in promise) Error: [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.
I also tried setting the scope with
worker.start({
serviceWorker: {
options: {
scope: "http://localhost:3001",
},
},
})
which resolves in an error
Failed to register a ServiceWorker: The origin of the provided scope ('http://localhost:3001') does not match the current origin ('http://localhost:8080').
Does anyone have experiences with this? Using service workers in remotes with module federation? How to call them in the container?
I was also experimenting with MSW (Mock Service Worker) for webpack 5 and module federation last couple of days. It may not apply to your specific use case, but below is what I did to make MSW work with a module federation app.
Set up and initiate MSW in the container app.
npx msw init ./ --save in the root of the host app (container).
Note that the directory of the installation should be the root - mockServiceWorker.js should be in the same location as the index.html (its location is specified in webpack config).This worked for me regardless of which child MFE apps calls the api endpoints you are intercepting with the MSW.
Below is the repo of a little experiment/example I did with Webpack5 Module Federation and MSW. https://github.com/nfabacus/module-federation-example
I did not test specifically with the module federation, but I think you can just follow the instruction in the MSW setup page for node (https://mswjs.io/docs/getting-started/install). Just install msw for each MFE and set up the tests. When I tested with normal react app (CRA), it worked fine (https://github.com/nfabacus/msw-cra-example). I don't think there is any difference between module federation and single SPA in terms of implementing msw with unit tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With