Post

MSW Always 404 on homepage setted Create-React-App

MSW Always 404 on homepage setted Create-React-App

Describe the bug

create-react-app with homepage setted causes MSW not to mock

Environment

react: “^18.3.1” msw: “^2.4.4” nodejs: 21.1.0

To Reproduce

  1. npx create-react-app mytestapp
  2. npm install msw@latest –save-dev
  3. npx msw init public –save
  4. Module not found: Error: Can’t resolve ‘graphql’ in
    mockup msw doesn’t work #82
    1
    2
    
    Hey!
    There are two things I recommend to solve this:
    
1
2
1. Use msw-storybook-addon.
2. Serve "public" since Storybook doesn't do that by default. I believe it's the "-p" flag in Storybook CLI.  
1
npm install --save graphql
  1. mymswtestapp/src/mocks/browser.js
1
2
3
4
import { setupWorker } from "msw/browser";
import { handlers } from "./handler";

export const worker = setupWorker(...handlers);
  1. mymswtestapp/src/mocks/handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { http, HttpResponse } from 'msw';

export const handlers = [
	http.post("api/code/NAT/:code", () => {
		return HttpResponse.json({
			"data": [
				{"CODE": "11", "DESCR": "UNIT1"},
				{"CODE": "22", "DESCR": "UNIT2"}
			]
		});
	}),

]
  1. mymswtestapp/index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

async function enableMocking() {
	if (process.env.NODE_ENV !== 'development') {
		return;
	}

	const { worker } = await import("./mocks/browser");

	let workerService = worker.start();
	console.log(worker.listHandlers());
	return workerService;
}

enableMocking().then(() => {

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
});
  1. in firefox, send request http://localhost:3000/api/code/NAT/1 can be succefully intercepted.

  2. But add "homepage": "myPage", to package.json will cause problem.

  3. Modify mytestapp/index.js:

According to the issue Wrong url for mockServiceWorker.js when base config set in Vite 5.x config #2055 and Using custom “homepage” property :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
async function enableMocking() {
	if (process.env.NODE_ENV !== 'development') {
		return;
	}

	const packageJson = await import("../package.json");
	const { worker } = await import("./mocks/browser");

	// `worker.start()` returns a Promise that resolves
	// once the Service Worker is up and ready to intercept requests.
	let workerService = worker.start({
	    serviceWorker: {
	    	// Provide a custom worker script URL, taking
	    	// the "homepage" into account.
	    	url: `${packageJson.homepage}/mockServiceWorker.js`,
	    },
	});
}

enableMocking().then(() => {

const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
});
  1. Now npm start still can start server, and show [MSW] Mocking enabled..
    But requests won’t intercepted.

Have studied

This post is licensed under CC BY 4.0 by the author.