Can't override existing handler (worker.use)
See original GitHub issueEnvironment
Name | Version |
---|---|
msw | 0.38.1 |
browser | Chrome |
OS | Mac OS |
I’m trying to mock out a Auth-Flow, where I want to change a handler dynamically on /login-Route. The component mounted on /login should change the existing handler from status 401 to 200.
However, worker.use(…) does not override. It seems to ADD another handler. If I log worker.printHandlers(); I see two handlers. One with the desired status of 200, but still a handler returning 401.
Both have the same url (/auth), but only the last one (401) seems to take action in the end, so I can’t mock out my flow.
Request handlers
import { SetupWorkerApi, setupWorker, rest } from 'msw';
let wrk: SetupWorkerApi = {} as SetupWorkerApi;
// Conditionally setup msw to keep it out of vite production bundle
if (import.meta.env.DEV) {
const handlers = [
rest.get('/auth', (_req, res, ctx) => res(ctx.status(401))),
];
// Configure a Service Worker with the given request handlers
wrk = setupWorker(...handlers);
// Store msw on window to access it in e2e-test
window.msw = {
worker: wrk,
rest,
};
}
export const worker = wrk;
Login component, that should change the /auth-handler
const Login = () => {
const [workerChanged, setWorkerChanged] = useState<boolean>(false);
useEffect(() => {
const { worker, rest } = window.msw;
worker.use(
rest.get('/auth', (req, res, ctx) => res(ctx.status(200)))
);
worker.printHandlers();
setWorkerChanged(true);
}, []);
return workerChanged ? <Navigate to="/" /> : null;
};
Current behavior
Override not working, initially described. The following screenshot shows the two handlers logged with worker.printHandlers();
Expected behavior
- Handler should be overridden, not added.
- Handler should return the desired 200 status
- worker.printHandlers(); should only show ONE handler
May be the same issue like in #1084.
I made sure I have only one MSW-instance running, at least I only have one “Mocking Enabled” log. Using vite as a bundler (HMR in dev mode) btw.
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
I changed the location of the app, but not with the browser router. That resulted in a complete refresh and thus creating a weird race condition between a useEffect and setupWorker.
Thank you for the fast reply. Found my issue^^.