Jest uses babel-jest plugin to compile JavaScript code using Babel.
You can find the ts-jest
process here, it will also use the babel-jest
processor at the end.
Babel
is written by JavaScript whose performance is slower than system-level languages such as Go
, and Rust
.
The transform process is slow(compared to system-level languages mentioned above), That's why your test suites running slowly.
Now I will use esbuild-jest as jest's transformer. Create two jest config files and compare the time cost.
jest.config.esbuild.js
:
module.exports = {
testEnvironment: 'jsdom',
transform: {
'^.+\\.tsx?$': 'esbuild-jest',
},
setupFilesAfterEnv: ['jest-extended'],
// coverageProvider: 'v8',
setupFilesAfterEnv: ['./jest.setup.js'],
};
jest.config.rtl.js
:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['jest-extended'],
setupFiles: ['./jest.setup.js'],
};
Using esbuild-jest
:
> jest --config jest.config.esbuild.js "--no-cache" "/workspaces/jest-v26-codelab/stackoverflow/72897761/routes.test.tsx"
PASS stackoverflow/72897761/routes.test.tsx
first
✓ Should test 404 route (32 ms)
✓ should render home page (10 ms)
✓ should render account detail page (3 ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 1.457 s
Time: 1.457 s
Using ts-jest
:
> jest --config jest.config.rtl.js "--no-cache" "/workspaces/jest-v26-codelab/stackoverflow/72897761/routes.test.tsx"
PASS stackoverflow/72897761/routes.test.tsx (11.246 s)
first
✓ Should test 404 route (32 ms)
✓ should render home page (8 ms)
✓ should render account detail page (4 ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 11.786 s
Time: 11.786 s
esbuild is faster than babel because it's written by Go. For more info, see Why is esbuild fast?
Jest caches transformed module files to speed up test execution. In order not to affect the test results, we use --no-cache
option to disable it.
P.S. ts-jest
may add esbuild
, see issue. And, take a look at this comment:
Not there yet, it will be opted in as experimental feature. esbuild doesn't support some TypeScript specific features which we need to be careful with adoption.