我正在尝试为 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
您可以按照以下步骤解决您的问题。
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
来开玩笑,这将在下一步中解释。
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.