使用 ts-jest 动态导入 ESM 来测试 CommonJS

问题描述 投票:0回答:1

给定一个使用 CommonJS 模块系统的库,但通过动态导入导入(仅)ESM 模块(以防止 TS 将

import
替换为
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;
    }
}

使用

ts-jest
运行单元测试的工作配置是什么?

我尝试了不同的组合(但失败了):

  1. Nodejs 选项
    --experimental-vm-modules

    错误:“jest 工作进程 (pid=2701) 被另一个进程终止:signal=SIGSEGV,exitCode=null。操作系统日志可能包含有关发生此情况的更多信息。”
  2. 开玩笑选项
    --runInBand

    错误:“测试环境已被拆除”
  3. 将笑话选项
    maxWorkers
    maxConcurrency
    设置为大值。
  4. 替代笑话预设

其他参考:

typescript jestjs ts-jest commonjs
1个回答
0
投票

开玩笑问题

  1. 安装需要的软件包:
npm install --save-dev jest ts-jest @types/jest

我们必须为此方法安装

ts.jest
jest

  1. 配置:
    使用使用
    jest.config.js
    来支持
    ts-jest
    的配置创建/更新
    TypeScript
    文件。

应该有效的示例配置:

module.exports = {
  preset: 'ts-jest/presets/default-esm',
  globals: {
    'ts-jest': {
      useESM: true,
    },
  },
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {},
  testEnvironment: 'node',
  extensionsToTreatAsEsm: ['.ts'],
  setupFilesAfterEnv: ['./jest.setup.js'],
};
  1. 调整测试脚本:
    package.json
    文件应如下所示:
"scripts": {
  "test": "jest --runInBand"
}
© www.soinside.com 2019 - 2024. All rights reserved.