Jest,ts-jest,带有 ES 模块导入的打字稿:找不到模块

Jest, ts-jest, typescript with ES Modules import : cannot find module

我很难开玩笑地使用带有 import 语法的 ES 模块的打字稿项目。 我的项目最初是为 commonjs 编写的,开玩笑测试 运行 没问题。但后来我决定改用 ES Modules(为了学习目的),jest 不开心ヽ(`Д´)ノ 我使用的工具:typescript, jest, ts-jest

问题始于 import 语法。

以下是我试过的代码。

//  projectRoot/src/app.ts

export default someFunction = (): void => {
   // some code
}

如果

// projectRoot/__tests__/app.test.ts

import someFunction from '../src/app';   // without file extension

/* This execute perfectly fine */

但是

// projectRoot/__tests__/app.test.ts

import someFunction from '../src/app.ts'   // with .ts

/*
● Test suite failed to run

   __tests__/app.test.ts:1:25 - error TS2691: An import path cannot end with a '.ts' extension. Consider importing '../src/app' instead.

    1 import information from '../src/app.ts';
*/

// projectRoot/__tests__/app.test.ts

import someFunction from '../src/app.js';   // with .js

/*
● Test suite failed to run

    Cannot find module '../src/app.js' from '__tests__/app.test.ts'
*/

如上例,如果我导入带有扩展名的模块(这是 ES 模块必须的),jest(或者可能是 ts-jest?)不高兴。 我在网上搜索了一下,但似乎是在开玩笑 doc is not very supportive for ES Modules. Same goes to ts-jest by this reading

我的项目结构:

/projectRoot
 ├── /src/app.ts
 ├── /__tests__/app.test.ts

内部 package.json 文件具有值 "type": "module"

tsconfig.json:

{
  "compilerOptions": {
     "target": "ES2015",
     "module": "ESNEXT",
     "outDir": "./build",
     "strict": true,
     "moduleResolution": "node",
     "esModuleInterop": true,
     "skipLibCheck": true,
     "forceConsistentCasingInFileNames": true
  },
  "include": ["./src"],
  "exclude": ["node_modules", "**/*.test.ts"]
}

jest.config.js

export default {
    "roots": [
      //"<rootDir>/src"
      "<rootDir>"
    ],
    "testMatch": [
      "**/__tests__/**/*.+(ts|tsx|js)",
      "**/?(*.)+(spec|test).+(ts|tsx|js)"
    ],
    "transform": {
      "^.+\.(ts|tsx)$": "ts-jest"
    },
    "preset": "ts-jest",
    "testEnvironment": 'node'
  }

请帮忙。谢谢。

下面导入

// projectRoot/__tests__/app.test.ts

import someFunction from '../src/app.js';   // with .js

ts-jest 可以配置为通过以下配置使用它。在 jest.config.js 文件中,添加以下内容:

module.exports = {
  //... // your previous configurations
  extensionsToTreatAsEsm: ['.ts'],
  globals: {
    'ts-jest': {
      //... // your other configurations here
      useESM: true,
    },
  },
  moduleNameMapper: {
    '^(\.{1,2}/.*)\.js$': '',
  }

这个配置的源码可以在ts-jest的文档页面找到:ESM-Support

我的一些示例代码如下:

// components_ts.ts
export add(x: number, y: number): number {
    return x + y;
}
// render_ts.ts
import * as ComponentsTS from './components_ts.js'; // <-- Extension is JS

export function addedNumbers(): number {
    let addedNumbers: number = ComponentsTS.add(1, 2);
    return addedNumbers;
}
// render_ts.test.ts
import * as RenderTS from '../ts_files/render_ts';

it ('Test addNumbers function', () => {
    expect(RenderTS.addedNumbers()).toBe(3);
});

运行 这与 npm jest