Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always 404 / Not Intercepted on homepage set CRA #2274

Open
4 tasks done
chiahao opened this issue Sep 10, 2024 · 5 comments
Open
4 tasks done

Always 404 / Not Intercepted on homepage set CRA #2274

chiahao opened this issue Sep 10, 2024 · 5 comments
Labels
bug Something isn't working needs:triage Issues that have not been investigated yet. scope:browser Related to MSW running in a browser

Comments

@chiahao
Copy link

chiahao commented Sep 10, 2024

Prerequisites

Environment check

  • I'm using the latest msw version
  • I'm using Node.js version 18 or higher

Browsers

Firefox, Safari

Reproduction repository

https://github.com/chiahao/mymswtestapp.git

Reproduction steps

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. mymswtestapp/src/mocks/browser.js
import { setupWorker } from "msw/browser";
import { handlers } from "./handler";

export const worker = setupWorker(...handlers);
  1. mymswtestapp/src/mocks/handler.js
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
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

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. Add "homepage": "myPage", to package.json.

  3. Modify mytestapp/index.js:

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.

Current behavior

Firefox get this:
Cannot POST /myPage/api/code/NAT/1

Expected behavior

"data": [
{"CODE": "11", "DESCR": "UNIT1"},
{"CODE": "22", "DESCR": "UNIT2"}
]

@chiahao chiahao added bug Something isn't working needs:triage Issues that have not been investigated yet. scope:browser Related to MSW running in a browser labels Sep 10, 2024
@kettanaito
Copy link
Member

Hi, @chiahao. Thanks for reporting this.

Can you please follow the Debugging runbook and let me know how far you got?

@chiahao
Copy link
Author

chiahao commented Sep 11, 2024

Hi, @kettanaito . Thanks for so fast response.

Modified browser.js:

import { setupWorker } from "msw/browser";
import { handlers } from "./handler";

export const worker = setupWorker(...handlers);
worker.events.on('request:start', async ({ request }) => {
  // Read the request body as text for every request
  // that occurs in your application.
  const payload = await request.clone().text()
});

worker.events.on('request:start', ({ request }) => {
  console.log('Outgoing:', request.method, request.url)
});

Test the version where the homepage is not set. The request is intercepted and shown in the console:
without_homepage_setting

But still, once homepage is set, the request is not intercepted:
with_homepage_setting

@chiahao chiahao changed the title Always 404 / Not Intercepted on homepage setted CRA Always 404 / Not Intercepted on homepage set CRA Sep 12, 2024
@chiahao
Copy link
Author

chiahao commented Sep 13, 2024

Hi, @kettanaito , does this test right?

@kettanaito
Copy link
Member

Can you please await the worker.start() promise? That doesn't look right.

@chiahao
Copy link
Author

chiahao commented Sep 19, 2024

Hi, @kettanaito ,

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

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.
	await worker.start({
		serviceWorker: {
			// Provide a custom worker script URL, taking
			// the "homepage" into account.
			url: `${packageJson.homepage}/mockServiceWorker.js`,
		},
	});
	console.log(worker.listHandlers());
}

enableMocking().then(() => {
	const root = ReactDOM.createRoot(document.getElementById('root'));
	root.render(
		<React.StrictMode>
			<App />
		</React.StrictMode>
	);
});

still no luck with await.
But there is a warning:
截圖 2024-09-20 清晨7 44 59

Does this mean MSW not support custom project path?
Thanks for any helping.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs:triage Issues that have not been investigated yet. scope:browser Related to MSW running in a browser
Projects
None yet
Development

No branches or pull requests

2 participants