给定一个使用 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
运行单元测试的工作配置是什么?
我尝试了不同的组合(但失败了):
--experimental-vm-modules
:--runInBand
maxWorkers
和 maxConcurrency
设置为大值。其他参考:
npm install --save-dev jest ts-jest @types/jest
我们必须为此方法安装
ts.jest
和 jest
。
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'],
};
package.json
文件应如下所示:"scripts": {
"test": "jest --runInBand"
}