Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 30 ยท Tooling and CI

TypeScript, Babel and CI

Run Jest on TypeScript with ts-jest, Babel or SWC, understand ESM mode, and set up Jest in GitHub Actions with caching and sharding, plus runnable transform and shard stand-ins.

Jest runs on Node.js, and Node cannot read TypeScript or JSX on its own. So whenever your source contains anything Node does not understand, Jest needs a transform: a step that converts each file to plain JavaScript just before it runs. Choosing that transform is the main TypeScript decision you will make.

The second half of this lesson moves from your laptop to a CI (continuous integration) server, where Jest must run unattended on every push. You will see a typical GitHub Actions workflow, how caching speeds it up, and how sharding splits a large suite across machines.

Real versus stand-in. Config files, YAML and commands are real but read-only: the site cannot install packages or run a pipeline. The TryIt blocks are honest toys: a mini transform with a cache, and a shard splitter. They show the ideas, not the real algorithms of Jest, Babel or ts-jest.

Three ways to run TypeScript

ts-jest Uses the TypeScript compiler. Type-checks.
Babel Strips types only. Fast, no checking.
SWC Rust-based and very fast. No checking.

Fast transforms pair well with a separate tsc step.

1 / 2

Option 1: ts-jest

ts-jest compiles each file with the real TypeScript compiler and, by default, reports type errors as test failures. That is a real benefit: a wrong argument type fails the run.

Terminal
npm install --save-dev jest typescript ts-jest @types/jest
npx ts-jest config:init
JavaScript
// jest.config.js
module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
};

A preset is a ready-made bundle of configuration. This one sets the transform for .ts files. The trade-off is speed: full type-checking per file is slower than just removing types, and large projects feel it. ts-jest has options to loosen this (for example, skipping type-checks in the test run and relying on a separate tsc --noEmit command), so read its documentation before tuning.

Option 2: Babel

Babel can also remove TypeScript syntax. Jest's default transform, babel-jest, uses your Babel config, so add the TypeScript preset:

JavaScript
// babel.config.js
module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript",
  ],
};

Babel only strips the types; it never checks them. A test suite can pass while tsc would reject the code. That is acceptable if your pipeline also runs tsc --noEmit as its own step. Babel's advantage is that one tool handles JSX, modern syntax and TypeScript, which many React setups already use.

Option 3: SWC

@swc/jest uses SWC, a very fast transpiler written in Rust. Like Babel, it removes types without checking them:

JavaScript
module.exports = {
  transform: {
    "^.+\\.(t|j)sx?$": "@swc/jest",
  },
};

On big codebases the speed difference can be large, because the transform step runs for every file that is not yet cached.

Choosing quickly

Need Reasonable choice
Type errors should fail tests ts-jest
Fastest feedback, types checked elsewhere SWC, or Babel if you already use it
React with JSX and TypeScript Babel or SWC
Small library, simple setup ts-jest

Whichever you choose, keep a tsc --noEmit script in your CI. Tests that run quickly and a type check that runs separately is a common and effective pairing.

Stand-in 1: a transform with a cache

What does a transform actually do? It maps source text to runnable text, and Jest caches the result on disk so unchanged files are skipped. The toy below removes a few simple type annotations with regular expressions (a real compiler parses the code properly, so never do this for real) and stores results keyed by a hash of the file content.

Node.js A toy transform and its cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Editing the file changes the hash, so the third run transforms again. Real Jest also includes the transformer version and your config in its cache key, which is why changing the config invalidates the cache. If you suspect a stale cache, run npx jest --clearCache.

ESM mode

Many packages now ship as ES modules (import / export), and Jest's default is still CommonJS (require). There are two ways to bridge the gap:

  1. Let a transform convert import to require. Babel and SWC do this by default, so most projects never notice.
  2. Run native ESM. Set "type": "module" in package.json and start Jest with a Node flag:
Terminal
node --experimental-vm-modules node_modules/jest/bin/jest.js

Native ESM support in Jest is still labeled experimental. Two practical consequences: jest.mock hoisting does not work the same way, and you mock ES modules with jest.unstable_mockModule instead. Mocking Modules covers the caveats. If you can stay on the transform route, it is the smoother path today.

Jest in GitHub Actions

A workflow file lives in .github/workflows/test.yml. This one installs dependencies with a cache and runs the tests:

YAML
name: Tests
on:
  push:
    branches: [main]
  pull_request:

jobs:
  jest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npx tsc --noEmit
      - run: npx jest --ci --coverage

What matters here:

  • npm ci installs exactly what the lock file says and fails if it is out of date. Use it instead of npm install in pipelines.
  • cache: npm in setup-node stores npm's download cache between runs.
  • --ci changes snapshot behavior: Jest will not write new snapshots automatically, so a missing snapshot fails the build instead of silently passing. See Snapshot Testing.
  • --coverage with a coverageThreshold (see Coverage and Test Quality) turns low coverage into a failing job.
  • --maxWorkers limits parallel workers. CI machines often have few cores, so a value such as --maxWorkers=2 can avoid memory trouble.

You can also cache Jest's own transform cache. Find its folder with npx jest --showConfig (look for cacheDirectory) and restore it with actions/cache, keyed by the lock file. The gain is largest when you use ts-jest or Babel on a big codebase.

Sharding big suites

When a suite takes too long on one machine, split it. --shard=1/3 tells Jest to run the first third of the test files, and a CI matrix runs three jobs in parallel:

YAML
    strategy:
      matrix:
        shard: [1, 2, 3]
    steps:
      # ...checkout, setup-node and npm ci as above...
      - run: npx jest --ci --shard=${{ matrix.shard }}/3

Each job runs a different slice of the files, so the wall-clock time drops roughly in proportion. Coverage is then per shard, so merging reports needs an extra step. Sharding splits whole test files, so one enormous file cannot be spread out; split it instead.

Stand-in 2: a shard splitter

The toy below distributes test files round-robin across shards after sorting them. Real Jest uses its own method to decide which files go to which shard, so the exact assignment differs, but the contract is the same: every file runs in exactly one shard.

Node.js Splitting test files into shards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Other CI habits

  • Print readable failures: Jest's default reporter works in CI logs, and many teams add a JUnit reporter so the CI system can show tests in its UI.
  • Fail on .only: the lint rule jest/no-focused-tests stops a stray it.only from silently skipping the rest. See describe, it and Test Organization.
  • Pin the Node version in CI to match development, since language features and the node: modules change between releases.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which transform type-checks your TypeScript by default?

    ts-jest uses the TypeScript compiler and reports type errors. Babel and SWC only remove type syntax.
  2. 2. Why use npm ci instead of npm install in a pipeline?

    npm ci gives reproducible installs, which is what automated builds need.
  3. 3. What does the --ci flag change about snapshots?

    With --ci, Jest refuses to create snapshots silently, so unreviewed snapshots cannot slip through in a pipeline.
  4. 4. You run jest --shard=2/4. What runs?

    Sharding splits whole test files into the given number of groups and runs one group per job.

Summary

  • Jest needs a transform for TypeScript and JSX: ts-jest type-checks, Babel and SWC only strip types and are faster.
  • Pair fast transforms with a separate tsc --noEmit step.
  • Native ESM needs --experimental-vm-modules and is still experimental; a transform that converts to CommonJS is the smoother route.
  • In GitHub Actions use npm ci, cache dependencies, and run jest --ci --coverage.
  • --shard=i/n splits test files across parallel jobs, and --clearCache resets a stale transform cache.

Next, put everything together by building and testing a module test-first in Project: Test a Shopping Cart.