Testing CommonJS with dynamic imports of ESM with ts-jest

183 Views Asked by At

Given a library that uses CommonJS module system, but imports ESM (only) modules with a dynamic import (to prevent TS from replacing import with require):

export async function loadEsmModule<T>(modulePath: string|URL): Promise<T> {
    const namespaceObject =
        (await new Function('modulePath', `return import(modulePath);`)(modulePath));

    // If it is not ESM then the values needed will be stored in the `default` property.
    if (namespaceObject.default) {
        return namespaceObject.default;
    } else {
        return namespaceObject;
    }
}

What is a working configuration to run unit tests with ts-jest using CommonJS?

What I tried in varying combinations (and failed):

  1. Nodejs option --experimental-vm-modules:
    Error: "A jest worker process (pid=2701) was terminated by another process: signal=SIGSEGV, exitCode=null. Operating system logs may contain more information on why this occurred."
  2. Jest option --runInBand
    Error: "Test environment has been torn down"
  3. Setting jest options maxWorkers and maxConcurrency to large values.
  4. Alternative jest presets

Other references:

0

There are 0 best solutions below