Jest 无法从 TypeScript ESM 路径映射导入模块

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

我正在尝试为 src 文件夹设置路径映射,但由于某种原因,在我的笑话测试文件中它没有被解析。

  • 这是我的项目结构:
app-esm/
├── __test__/
│   └── index.test.ts
├── src/
│   └── index.ts
├── jest.config.ts
├── package.json
└── tsconfig.json
  • 这是我的配置:

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "dist",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "paths": {
      "@App/*": ["src/*"]
    }
  },
  "exclude": ["node_modules", "./*.ts", "__test__"]
}

jest.config.ts

import type { JestConfigWithTsJest } from "ts-jest";

const config: JestConfigWithTsJest = {
  verbose: true,
  transform: {
    "^.+\\.ts?$": [
      "ts-jest",
      {
        useESM: true,
      },
    ],
  },
  extensionsToTreatAsEsm: [".ts"],
  moduleNameMapper: {
    "@App/(.*)": "<rootDir>/src/$1",
  },
};

export default config;

索引文件

export const run = () => "hello, there!";

测试文件

import { run } from "@App/index";

test("index", () => {
  expect(run()).toBe("hello, there!");
});

这里缺少什么配置?

您可以查看此repo来重现该问题。

p.s 无需路径映射即可完美导入。我只需要从 tsconfig 中删除路径配置并用 "^(\\.{1,2}/.*)\\.js$": "$1".

 替换 
moduleNameMapper

@App
typescript jestjs ts-jest tsconfig tsconfig-paths
1个回答
0
投票

您可以按照以下步骤解决您的问题。

  1. 将您的
    jest.config.ts
    更新为如下所示:
import type { JestConfigWithTsJest } from "ts-jest";

const config: JestConfigWithTsJest = {
  verbose: true,
  transform: {
    '^.+\\.(t|j)s$': ['ts-jest', {
      tsconfig: './tsconfig.test.json',
      useESM: true,
    }],
  },
  moduleNameMapper: {
    "@App/main/main": "<rootDir>/src/main/main",
    "@App/(.*)": "<rootDir>/src/$1",
  },
  preset: "ts-jest/presets/default-esm",
};

export default config;

这里有两个修复。一个用于

moduleNameMapper
,另一个用于
preset
使用 ESM。

我们还将使用新的

tsconfig.test.json
来开玩笑,这将在下一步中解释。

  1. 我创建了一个新的
    tsconfig.test.json
    (因为在您现有的
    tsconfig.json
    中,我看到您已排除了
    __test__
{
  "extends": "./tsconfig.json",
  "include": ["__test__"]
}

运行

npm run test
时,您会得到以下输出:

> [email protected] test
> node --experimental-vm-modules node_modules/.bin/jest

(node:12578) ExperimentalWarning: VM Modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 PASS  __test__/main/main.test.ts
  ✓ main (1 ms)

  console.log
    Hello, Mock!

      at src/index.ts:3:9

  console.log
    Hello, Mock namedExport!

      at src/index.ts:4:9

 PASS  __test__/index.test.ts
  ✓ main (11 ms)

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.169 s, estimated 1 s
Ran all test suites.
© www.soinside.com 2019 - 2024. All rights reserved.