How to Use `import.meta` When Testing With Jest

We are using import.meta.url to make use of web workers, for example using the native worker support in Webpack 5. That works great but fails when running the Jest tests.

babel-vite-preset does not handle this as far as I can tell. The top answer about extracting and mocking the code that uses import.meta does work but is unwieldy.

I found the currently best solution is to use babel-plugin-transform-import-meta. That simple plugin replaces the import.meta.url syntax with Node.js code to retrieve the URL to the current file, so it works nicely in tests. Note that you will only want to have this plugin active when running the tests.

Leave a Comment