title: Mocking ES Modules when running the Vite development server
body: <p>I need to find out how I can instruct Vite to replace references to local/relative modules at runtime. The use case here is the test runner <a href="https://github.com/larsthorup/mocha-vite-puppeteer" rel="nofollow noreferrer">mocha-vite-puppeteer</a>, which uses Vite to run tests, but then stubbing of modules of course does not work when using Node machinery such as proxyquire or rewire.</p>
  <p>So I basically need to either be tipped of some existing software that can help me in doing this, or some tips on how to create my own &quot;vite-proxyquire&quot; using <code>import.meta</code> and friends.</p>
  <p>A normal use for temporarily stubbing out <code>./my-ugly-module</code> might be that you want to avoid loading some sub-dependency that has some ugly transitive dependencies that suck the entire application tree into your little test, or you want to avoid loading a sub-dependency that has some ugly side effects on the global state.</p>
  <h1>Existing solutions</h1>
  <p><a href="https://modern-web.dev" rel="nofollow noreferrer">Modern Web</a>, a refreshing &quot;bundler- and frameworkless&quot; approach to web development using standard tools, talk a bit about the issue around how the immutable nature of ES Modules prevent usual stubbing patterns. They present a solution in the form of <em>Import Maps</em>, which essentially would be similar to the alias config in Vite (Rollup really), mapping a path to a module to some other file. The problem with a static solution like this is that it would replace <em>all</em> imports of a given module, not just for a single test. <a href="https://modern-web.dev/docs/test-runner/writing-tests/mocking/" rel="nofollow noreferrer">Modern Web has a solution to this</a> where they have chosen to use a custom html page for each such test. To make this less of a hassle with regards to running, they then have a custom test runner that handles dealing with all these extra test html files. Doing something like that could be one way of fixing it, but it would require developing quite a bit of middleware/plugin code IMHO to make it work transparently with Vite. Without any advanced tooling it would also introduce a lot of extra files that seems a bit of a downside compared to todays imperative mocking of dependencies with proxyquire, Jest or Test Double from inside of the test files.</p>