上下文:我在我的项目中使用了jest、typescript、babel和material-ui。
我一直在调查我们的单元测试的一个性能问题,这个问题似乎是由大多数单元测试导入整个material-ui造成的,因为我们是从@material-ui/core导入它们的。我一直试图用一个巴别塔插件来解决这个问题,不管是使用自定义插件还是babel-plugin-transform-imports包,它似乎也能做我想要的事情。
问题是这个插件似乎从未被调用过。我们使用ts-jest,所以它同时通过babel和typescript编译器。但似乎typescript可能会在babel转换它们之前解决所有的导入。
我已经考虑过只使用babel来完成所有的typescript编译,但随后将jest构建过程与我们使用的主要构建过程分开维护。不管怎样,我现在遇到了让它正常运行的问题。我也在考虑做一个自定义的jest转换器,但它似乎比babel插件更脆弱,更难维护。
Jest配置:
"preset": "ts-jest",
"globals": {
"ts-jest": {
"babelConfig": {
"presets": [
"@babel/react",
"@babel/env"
],
"plugins": [
"@babel/plugin-transform-spread",
"./customPlugin.js"
]
},
"isolatedModules": true
}
},
"testEnvironment": "jsdom",
"collectCoverageFrom": [
<coverage paths>
],
"setupFiles": [
<setup files>
],
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"moduleNameMapper": {
<mappers>
},
"coverageDirectory": "./test/coverage",
"testResultsProcessor": "./node_modules/jest-html-reporter",
"transform": {
"^.+\\.tsx?$": "ts-jest",
".+\\.jsx?$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileTransformer.js"
},
"testRegex": "/src/.*\\.spec\\.(ts|tsx)$",
"snapshotSerializers": [
"enzyme-to-json/serializer"
]我的tsconfig文件:
{
"compilerOptions": {
"sourceMap": true,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"jsx": "react",
"lib":[ "es2015", "dom" ,"es2017"],
"target": "es5",
"resolveJsonModule": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "./dist",
"baseUrl": ".",
"paths": {
<custom paths>
}
},
"include": [
"src/**/*"
],
"exclude": [
"**/*.spec.ts",
"**/*.spec.tsx"
]
}发布于 2021-06-23 23:22:48
看起来我误解了typescript编译器的输出。typescript编译器将我所有的导入语句转换为requires,所以我的寻找ImportDeclaration访问者的babel插件最终什么也没做。
我还发现ts-jest还有一个选项可以在typescript上指定一个ast转换器:https://kulshekhar.github.io/ts-jest/docs/processing/
https://kulshekhar.github.io/ts-jest/docs/getting-started/options/astTransformers
https://levelup.gitconnected.com/writing-typescript-custom-ast-transformer-part-1-7585d6916819
https://stackoverflow.com/questions/68071764
复制相似问题