导入自定义Angular库至Jest单元测试时遇Unexpected Token错误
错误信息
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformationDetails:
C:\Users\user\Desktop\app\node_modules@my-namespace\custom-lib\index.d.ts:5
export * from './public-api';
^^^^^^SyntaxError: Unexpected token 'export'
14 | import { NoopAnimationsModule } from '@angular/platform-browser/animations';
16 | import { CustomPipe } from "@my-namespace\custom-lib";
自定义库结构(node_modules中)
|--@my-namespace |--custom-lib |--esm2020 |--fesm2015 |--fesm2020 |--lib |--index.d.ts |--public-api.d.ts |--package.json
注:库的package.json中main字段为"index.d.ts"
当前Jest配置
import type { Config } from 'jest'; const config: Config = { preset: 'jest-preset-angular', setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'], testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/'], coveragePathIgnorePatterns: ['<rootDir>/src/app/modules/core/swagger-api'], moduleNameMapper: { '^@environments/(.*)': '<rootDir>/src/environments/$1', '^@app/(.*)': '<rootDir>/src/app/$1' }, testMatch: [ '**/__tests__/**/!(DISABLED.)*.[jt]s?(x)', '**/!(DISABLED.)?(*.)+(spec|test).[tj]s?(x)' ], globals: { 'ts-jest': { tsconfig: '<rootDir>/tsconfig.spec.json', stringifyContentPathRegex: '\\.html$' } } }; export default config;
tsconfig.spec.json配置
{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": ["jest", "node"] }, "files": ["src/polyfills.ts"], "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] }
版本信息
jest 28.1.3jest-preset-angular 12.2.3
已尝试将库添加到transformIgnorePatterns但未生效,库结构与@ngx-translate/core几乎一致,后者可正常配合Jest使用,求解决思路。
解决思路
1. 修正库的package.json入口配置
当前库的main字段指向index.d.ts(类型定义文件),而非可执行的JS代码。Angular库需在package.json中正确配置多环境入口,示例:
{ "main": "./fesm2020/custom-lib.mjs", "module": "./fesm2020/custom-lib.mjs", "es2020": "./fesm2020/custom-lib.mjs", "typings": "./index.d.ts", "exports": { ".": { "types": "./index.d.ts", "esm2020": "./esm2020/custom-lib.mjs", "es2020": "./fesm2020/custom-lib.mjs", "node": "./fesm2020/custom-lib.mjs", "default": "./fesm2020/custom-lib.mjs" } } }
让Jest加载编译后的ES模块文件,而非直接解析d.ts文件。
2. 调整Jest的transformIgnorePatterns配置
默认Jest忽略node_modules下的文件转换,需明确让Jest处理你的自定义库,修改配置:
const config: Config = { // ...其他配置 transformIgnorePatterns: [ '<rootDir>/node_modules/(?!@my-namespace/custom-lib)' ] };
通过负向断言排除目标库,让jest-preset-angular的转换器处理它。若需匹配@my-namespace下所有包,可写成(?!@my-namespace)。
3. 用moduleNameMapper直接映射到ES模块
若暂时无法修改库的package.json,可在Jest配置中直接映射到库的编译后文件:
moduleNameMapper: { // ...其他映射 "^@my-namespace/custom-lib$": "<rootDir>/node_modules/@my-namespace/custom-lib/fesm2020/custom-lib.mjs" }
4. 检查tsconfig.spec.json的ES模块配置
确保继承的tsconfig.json中开启esModuleInterop: true,若未开启,可在tsconfig.spec.json中补充:
"compilerOptions": { // ...其他配置 "esModuleInterop": true }
这有助于Jest正确处理ES模块的导入逻辑。
内容的提问来源于stack exchange,提问作者Bendegúz Góczi

