Context: I'm using jest, typescript, babel, and material-ui in my project.
I've been investigating a performance issue with our unit tests that seem to be caused by most unit tests importing the entirety of material-ui because we're importing them from @material-ui/core. I've been trying to resolve this with a babel plugin, either using a custom plugin or the babel-plugin-transform-imports
package which seems like it would do what I want as well.
The trouble is that the plugin never seems to be called. We're using ts-jest, so it goes through both the babel and typescript compilers. But it seems like typescript might be resolving all of the imports before babel can transform them.
I've considered just using babel to do all of the typescript compilation, but then have maintain the jest build process separately from the main build process that we use. And I'm currently having issues getting it to run properly anyway. I'm also considering doing a custom jest transformer, but that seems like it would be more fragile and harder to maintain than a babel plugin.
Jest configuration:
"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"
]
My tsconfig file:
{
"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"
]
}
It looks like I was misunderstanding the output from the typescript compiler. The typescript compiler was converting all of my import statements into requires, so my babel plugin which was looking for ImportDeclaration
visitor wasn't ending up doing anything.
I also found that ts-jest has an option to specify an ast transformer on the typescript as well: 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