Cannot dynamically import module in jest tests.
Steps to reproduce the behavior:
test('dynami', async () => {
const tenderElement = await import('mymodule');
});
Throws:
% npx jest test/dy.spec.js
(node:25196) ExperimentalWarning: The ESM module loader is experimental.
FAIL test/dy.spec.js
✕ dynami (1ms)
● dynami
TypeError: A dynamic import callback was not specified.TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]: A dynamic import callback wa
s not specified.
1 | test('dynami', async () => {
> 2 | const tenderElement = await import('mymodule');
| ^
3 | });
at Object.<anonymous> (test/dy.spec.js:2:27)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.313s, estimated 1s
Ran all test suites matching /test\/dy.spec.js/i.
Expected the dynamic import to work.
% npx envinfo --preset jest
npx: installed 1 in 0.696s
System:
OS: Linux 5.3 Manjaro Linux
CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Binaries:
Node: 13.7.0 - /usr/bin/node
Yarn: 1.22.0 - /usr/bin/yarn
npm: 6.13.6 - /usr/bin/npm
npmPackages:
jest: ^24.9.0 => 24.9.0
It seems that this is a known issue: https://github.com/facebook/jest/issues/9430
Essentially the same as above, but passed as importModuleDynamically when constructing the module. Will also support jest.mock, jest.resetModules etc more cleanly, so likely to be used quite a bit.
This can also be done for vm.Script via the same option.
Correct, this is blocked by #9430. For now you'll need to transpile it (using Babel, TypeScript, or something else like it)
It's not clear that there is a method that works... an alternative workaround is perhaps to use .mjs instead of .js.
dynamic import has been implemented in #10620, released in 26.5.3
Most helpful comment
dynamic import has been implemented in #10620, released in 26.5.3