如何解决使用 ts-jest
上下文:我在我的项目中使用了 jest、typescript、babel 和 material-ui。
我一直在调查我们的单元测试的性能问题,这似乎是由大多数单元测试导入整个 material-ui 引起的,因为我们是从 @material-ui/core 导入它们。我一直在尝试使用 babel 插件解决这个问题,无论是使用自定义插件还是 babel-plugin-transform-imports
包,这似乎也能满足我的需求。
问题是插件似乎永远不会被调用。我们使用 ts-jest,所以它通过 babel 和 typescript 编译器。但似乎 typescript 可能会在 babel 转换它们之前解析所有导入。
我考虑过只使用 babel 来完成所有的打字稿编译,但随后将 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"
]
{
"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"
]
}
解决方法
看起来我误解了打字稿编译器的输出。打字稿编译器正在将我所有的导入语句转换为需要,所以我的 babel 插件正在寻找 ImportDeclaration
访问者并没有做任何事情。
我还发现 ts-jest 也有一个选项可以在打字稿上指定一个 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。