网站搜索

jestjs - Jest, ts-jest, 使用 ES 模块导入 TypeScript:找不到模块


我在使用 import 语法让 Jest 处理 TypeScript ES 模块项目时遇到了困难。我的项目最初是为 CommonJS 编写的,Jest 测试运行良好。但后来我决定改用ES模块(出于学习目的),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?)就不会高兴。我在网上查了一下,但似乎 jest 的文档对 ES 模块支持不是很好。根据阅读,ts-jest 也是如此。

我的项目结构:

/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'
  }

请帮忙。谢谢。

答案#1

使用下面的导入

// 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$': '$1',
  }

此配置的来源可以在 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 运行这个

相关文章