Replies: 1 comment 1 reply
-
Thanks for sharing your experience and solution 🎉 I'm also experimenting with Vitest browser mode + MSW. Still doing some initial configuration and troubleshooting, but seeing others are engaging in this space is very encouraging. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
EDIT: Actually, I realised this is more of an MSW issue than a Vitest issue. I ended up writing a little NPM package that solves the problem: https://www.npmjs.com/package/isomorphic-msw
Hey there!
I'm trying to figure out how to set up a Vitest workspace with two projects - one using Vitest Browser mode, another using
happy-dom
, but both running the same exact test suite.I have an example repo to provide context for this question, where you can run my setup and try it for yourself:
The Vitest workspace config I've got is actually pretty simple:
I also want to use MSW to mock API responses, so I need to be able to switch between using
setupServer()
andsetupWorker()
depending on the test environment, and I also need a reference to the created server or worker so that I can callserver.use()
orworker.use()
during test setup.I thought I would be able to achieve this by writing a helper function that imports
@vitest/browser/context
, checking to see if theserver
export is defined, and choosing the MSW API to use as appropriate. Something like this:But unfortunately, this kind of setup will result in two similar errors, seemingly caused by Vitest trying to bundle both versions of MSW for both Vitest projects:
After some digging, I found a suggestion in this comment to use
resolve.alias
to force these imports to resolve to something. After all, the imports that are failing are not actually used, so I can just alias them to a dummy module:This feels really gross, but it does work: https://github.com/ezzatron/vitest-msw-server-and-worker-config/actions/runs/10899426826/job/30244789376#step:3:216
For reference, here's what a run looks like without the
resolve.alias
config additions: https://github.com/ezzatron/vitest-msw-server-and-worker-config/actions/runs/10899434546/job/30244811169#step:3:216Now that you've read through that wall of text (sorry), is there something I'm missing here in Vitest or Vite config that could simplify this setup?
Beta Was this translation helpful? Give feedback.
All reactions