'Jest: How to transform import.meta.url using Next 12 with SWC
I am using Jest in a Next.js 12 App with the Rust Compiler.
Since I'm using WebWorkers I have a file in which I use import.meta.url.
to construct the worker
The problem with that is, that Jest will throw an error stating I can't use import.meta.url
outside an ES Module (Since it still transforms the typescript code to commonJs) I saw that one could add a babel plugin which would then transform those files which include import.meta.url
. https://github.com/facebook/jest/issues/12183#issuecomment-1004320665
But I would prefer not using Babel, since I use the Jest config from Next which is using the rust compiler. Also I am not sure if I can even use this babel plugin in this configuration.
I also know that one could configure jest to use ESModules instead but I don't want to use this method either since it's experimental and produces some strange errors in my project.
So I want to know: Is there a way (or better a SWC plugin) to use this transformation with SWC?
Solution 1:[1]
A solution that doesn't require massive changes to the application or testing configuration is to refactor the import.meta.url
call into a helper module, and when testing the original file, mock the helper module. Here's the general idea.
// my-module.js
import { importMetaUrl } from './import-meta-url'
export function foo() {
return importMetaUrl()
}
// import-meta-url.js
export function importMetaUrl() {
return import.meta.url
}
// my-module.test.js
import { foo } from './my-module'
jest.mock('./import-meta-url', () => ({
importMetaUrl: () => 'http://www.example.org'
})
test('test', () => {
expect(foo()).toEqual('http://www.example.org')
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |