'Testing Svelte components with dynamically imported components in jest (await import)
I'm writing a test in jest for a svelte component which dynamically imports another component. The following snippet is the part where the dynamic import happens.
async function importComponent() {
if (!dynamicComponent) {
dynamicComponent= (await import('../Component')).Component;
}
}
my jest config (in package.json)
"jest": {
"globals": {
"ts-jest": {
"isolatedModules": true,
"tsConfig": "./tsconfig.json",
}
},
"testEnvironment": "jsdom",
"verbose": true,
"transform": {
"^.+\\.svelte$": [
"svelte-jester",
{
"preprocess": true
}
],
"^.+\\.ts$": "ts-jest",
"^.+\\.js$": "babel-jest"
},
"setupFilesAfterEnv": [
"<rootDir>/setupTests.ts"
],
"moduleFileExtensions": [
"js",
"ts",
"svelte"
]
}
The failing test
it('should open on click', async () => {
const { getByRole } = render(ComponentUnderTest, { ...dummyProps });
const loadComponentButton = getByRole('button');
await fireEvent(loadComponentButton, new MouseEvent('click', {
bubbles: true,
cancelable: true,
}));
});
I tried to solve the problem with babel plugins "dynamic-import-node"
and/or "@babel/plugin-syntax-dynamic-import"
. But the result is the same.
I also tried to use jest-next-dynamic
(which is used for mocking dynamic imports with the nextjs dynamic import syntax)
I also tried to mock the dynamic import but without any success - or rather I didn't know how to mock the import...
It is not important to me if I actually import the component during the testrun, preload the component or just mock it - the test should just run without throwing errors
Please let me know if I should provide any additional information!
Update
The Test fails with the following message:
Error: You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules.
I'm running Node v16.4.2 btw - I tried the solution described in the link but the result was that all test were failing. Maybe my understanding of how the test is executed is wrong but I run the tests in in the jsdom-environment and not in a node environment so I don't really get the error?
At the moment my goal is to just mock import()
somehow.
UDPATE: Workaround suggested by @DavidDalBusco in the comments
Ultimately I moved the lazy import in a middle / proxy file. In that way I can mock the lazy loading part and test my component and on the other way can write dedicated tests for my services. – David Dal Busco
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|