Jest is a JavaScript testing framework that provides test discovery, assertions, mocking, snapshot testing, code coverage, and execution management. SWC is a high-performance JavaScript and TypeScript compiler written in Rust. The @swc/jest package connects these two tools by allowing Jest to transform source files with SWC instead of relying on Babel or executing untransformed source code.
The integration is particularly useful in projects that already use SWC for development and production builds. A shared transformation strategy reduces configuration duplication and makes test execution more representative of the application’s actual compilation environment.
Jest does not natively understand every syntax extension used in modern JavaScript projects. Depending on the runtime and configuration, source files may contain:
Jest uses transformers to convert source files into executable JavaScript. A transformer receives source code and transformation options and returns JavaScript that Jest can execute.
The @swc/jest package implements this transformer interface using @swc/core.
The transformation pipeline can be represented as follows:
Test source files
|
v
Jest
|
v
Transformer selection
|
v
@swc/jest
|
v
@swc/core
|
v
JavaScript transformation
|
v
Jest runtime
|
v
Test execution
|
v
Assertions and results
SWC handles syntax transformation, while Jest remains responsible for the testing lifecycle.
This separation is important. SWC does not replace Jest’s assertion system, test runner, mocking facilities, or test environment. It only changes how source files are compiled before execution.
A typical TypeScript project requires Jest, the SWC compiler, the Jest transformer, and TypeScript itself.
The development dependencies can be installed with npm:
npm install --save-dev jest @swc/core @swc/jest typescript @types/jest
The packages have distinct responsibilities:
| Package | Responsibility |
|---|---|
jest |
Test runner, assertions, mocking, and coverage |
@swc/core |
SWC compiler implementation |
@swc/jest |
Jest transformer based on SWC |
typescript |
TypeScript compiler and type-checking |
@types/jest |
TypeScript declarations for Jest APIs |
The @swc/core package is a direct dependency of the transformer and is also useful when SWC is used independently for other build tasks.
For JavaScript-only projects, TypeScript and @types/jest are unnecessary.
For projects using JSX with a DOM-like test environment, Jest’s environment package may also be required:
npm install --save-dev jest-environment-jsdom
Modern Jest installations treat jest-environment-jsdom as a separate package rather than assuming that it is included with Jest.
A typical project structure is:
project/
├── src/
│ ├── components/
│ │ └── Button.tsx
│ ├── services/
│ │ └── userService.ts
│ └── utils/
│ └── format.ts
├── tests/
│ └── format.test.ts
├── .swcrc
├── jest.config.js
├── package.json
└── tsconfig.json
The separation between application source code and tests is optional. Jest can discover tests in many directory layouts through its configuration.
The main SWC configuration is usually stored in .swcrc.
This file describes how SWC parses and transforms source code. The configuration can be shared with other tools, although test-specific requirements sometimes justify a separate configuration.
A basic TypeScript configuration is:
{
"jsc": {
"parser": {
"syntax": "typescript"
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
The configuration contains two primary sections.
The jsc section controls JavaScript and TypeScript parsing and transformation.
The parser specifies TypeScript syntax. The target specifies the ECMAScript version for generated JavaScript.
The module section controls module transformation.
The commonjs setting converts ES module imports and exports into CommonJS-compatible output. This is a common choice for Jest projects that use its traditional CommonJS execution model.
The es2022 target is an example rather than a universal requirement. The target should reflect the Node.js version used by the test environment and the syntax transformation required by the application.
For a project containing both TypeScript and TSX files, JSX parsing must also be enabled:
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"transform": {
"react": {
"runtime": "automatic"
}
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
The tsx option allows the TypeScript parser to recognize JSX syntax in TypeScript files.
The React transformation configuration enables the automatic JSX runtime. Under this configuration, JSX expressions are transformed without requiring an explicit React import in every component.
For example:
type ButtonProps = {
label: string;
disabled?: boolean;
};
export function Button({
label,
disabled = false
}: ButtonProps) {
return (
<button disabled={disabled}>
{label}
</button>
);
}
SWC transforms the JSX into JavaScript calls compatible with the automatic React runtime.
The actual React runtime must still be available at execution time. SWC does not install React or provide a component rendering environment.
Jest uses its transform configuration property to select the transformer for matching files.
A basic configuration can be defined in jest.config.js:
module.exports = {
testEnvironment: "node",
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
testMatch: [
"**/?(*.)+(spec|test).[tj]s?(x)"
]
};
The regular expression matches common JavaScript and TypeScript source extensions:
.js.jsx.ts.tsxWhen Jest encounters a matching file, it invokes @swc/jest.
The testEnvironment property specifies the execution environment. The node environment is appropriate for services, utilities, server-side modules, and other code that does not require browser APIs.
The testMatch property defines the patterns used to discover test files.
An equivalent configuration can use the more compact testRegex option, but testMatch is often easier to maintain when projects have several test naming conventions.
The Jest configuration can also explicitly provide SWC options:
module.exports = {
testEnvironment: "node",
transform: {
"^.+\\.(t|j)sx?$": [
"@swc/jest",
{
jsc: {
target: "es2022",
parser: {
syntax: "typescript"
}
},
module: {
type: "commonjs"
}
}
]
}
};
This approach is useful when the transformation configuration should be isolated from the application’s general SWC configuration.
When transformer options are supplied directly, they should contain the complete configuration required for that transformation. They should not be assumed to inherit every setting from .swcrc.
For maintainability, a shared .swcrc is generally preferable when the same compilation behavior is required across development, production, and testing.
After installing the dependencies and configuring SWC, a TypeScript module can be tested directly.
Consider a utility that formats monetary values:
export function formatPrice(
amount: number,
currency = "USD"
): string {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency
}).format(amount);
}
The corresponding test can be written as:
import { formatPrice } from "../src/utils/format";
describe("formatPrice", () => {
it("formats a monetary value", () => {
expect(formatPrice(1250)).toBe("$1,250.00");
});
it("supports another currency", () => {
expect(formatPrice(1250, "EUR")).toBe("€1,250.00");
});
});
Jest discovers the test file, passes it through @swc/jest, and executes the resulting JavaScript.
The TypeScript annotations and function signatures are removed during transformation. Jest receives executable JavaScript rather than TypeScript source code.
A corresponding package configuration might look like this:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
}
}
The test suite can be executed with:
npm test
Watch mode can be started with:
npm run test:watch
Coverage can be collected with:
npm run test:coverage
The scripts invoke Jest, which selects @swc/jest for the matching source files.
SWC supports multiple syntax modes. The parser configuration must correspond to the actual source files.
A JavaScript project does not need TypeScript parsing:
{
"jsc": {
"parser": {
"syntax": "ecmascript",
"jsx": true
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
The jsx option enables JSX parsing for JavaScript files.
A TypeScript project without JSX uses:
{
"jsc": {
"parser": {
"syntax": "typescript"
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
A TypeScript project with JSX uses:
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
The parser options are not interchangeable in every situation.
In particular, TSX parsing interprets angle-bracket syntax differently from ordinary TypeScript parsing. Type assertions using angle brackets are not supported in TSX files because they conflict with JSX syntax.
The alternative as syntax avoids this ambiguity:
const value = input as string;
A project may contain JavaScript, TypeScript, JSX, and TSX files simultaneously.
SWC can handle these files through separate overrides or a common parser strategy when the syntax permits it.
For complex mixed projects, explicit transformer selection is often easier to reason about:
module.exports = {
transform: {
"^.+\\.tsx?$": [
"@swc/jest",
{
jsc: {
parser: {
syntax: "typescript",
tsx: true
},
target: "es2022"
},
module: {
type: "commonjs"
}
}
],
"^.+\\.[jt]sx?$": [
"@swc/jest",
{
jsc: {
parser: {
syntax: "ecmascript",
jsx: true
},
target: "es2022"
},
module: {
type: "commonjs"
}
}
]
}
};
The order of transformer patterns matters because Jest applies the first matching transform rule. The broader JavaScript pattern must not precede the TypeScript-specific pattern if both can match the same file.
The second pattern can match TypeScript extensions as well, so the first rule must be positioned before it.
For projects without unusual parser requirements, a single transformer configuration is usually simpler.
SWC can transform React components written in JSX or TSX.
However, transforming JSX is not equivalent to providing a browser environment. React component tests may require a DOM implementation and a rendering library.
A typical React testing setup uses:
jest-environment-jsdom for browser-like DOM APIs.The required packages can be installed with:
npm install --save-dev jest-environment-jsdom \
@testing-library/react \
@testing-library/jest-dom
A Jest configuration for a React application can be written as:
module.exports = {
testEnvironment: "jsdom",
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
setupFilesAfterEnv: [
"<rootDir>/tests/setup.ts"
],
testMatch: [
"**/?(*.)+(spec|test).[tj]s?(x)"
]
};
The setup file registers additional DOM assertions:
import "@testing-library/jest-dom";
A component test can then verify rendered output and user interaction:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Button } from "../src/components/Button";
describe("Button", () => {
it("renders its label", () => {
render(<Button label="Save" />);
expect(
screen.getByRole("button", { name: "Save" })
).toBeInTheDocument();
});
it("can be disabled", () => {
render(
<Button
label="Save"
disabled
/>
);
expect(
screen.getByRole("button", { name: "Save" })
).toBeDisabled();
});
});
The example uses React Testing Library to render the component and query the resulting DOM.
SWC performs the TSX transformation, Jest executes the test, and jsdom provides the simulated browser environment.
The testing environment and the compiler have independent responsibilities. A component can compile successfully with SWC but still fail when executed because a browser API, React dependency, or DOM feature is missing.
SWC can transform modern JavaScript syntax according to a selected compilation target.
For example, optional chaining and nullish coalescing are widely used in contemporary JavaScript:
type User = {
profile?: {
displayName?: string;
};
};
export function getDisplayName(
user: User
): string {
return user.profile?.displayName ?? "Anonymous";
}
The function safely accesses nested properties and returns a fallback when the display name is absent or null.
A test verifies the behavior:
import { getDisplayName } from "../src/utils/user";
describe("getDisplayName", () => {
it("returns the configured display name", () => {
expect(
getDisplayName({
profile: {
displayName: "Alex"
}
})
).toBe("Alex");
});
it("returns a fallback for missing profiles", () => {
expect(
getDisplayName({})
).toBe("Anonymous");
});
});
The target configuration determines whether SWC needs to transform particular language features.
A newer target generally results in less transformation and smaller generated output. An older target may require additional syntax transformations.
The target should be compatible with the Node.js runtime executing Jest. Setting an unnecessarily old target can increase compilation work without improving test compatibility.
It is also important to distinguish syntax transformation from runtime polyfills.
SWC can transform syntax such as optional chaining, but it does not automatically provide every missing built-in API. For example, transforming code that uses a newer built-in method does not necessarily provide an implementation of that method in an older Node.js runtime.
Polyfills and runtime compatibility remain separate concerns.
One of the most important distinctions in the integration is that SWC transforms TypeScript syntax but does not perform TypeScript type checking.
Consider the following module:
export function calculateTotal(
price: number,
quantity: number
): number {
return price * quantity;
}
The type annotations are removed during transformation.
The generated JavaScript behaves essentially like:
export function calculateTotal(price, quantity) {
return price * quantity;
}
SWC does not verify that callers pass numbers, that interfaces are implemented correctly, or that generic constraints are satisfied.
Consequently, a project using @swc/jest should generally run TypeScript type checking as a separate task.
A suitable tsconfig.json might contain:
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"types": [
"jest",
"node"
]
},
"include": [
"src",
"tests"
]
}
The noEmit option prevents TypeScript from generating JavaScript files. The compiler performs type checking only.
The package scripts can run testing and type checking independently:
{
"scripts": {
"test": "jest",
"typecheck": "tsc --noEmit",
"validate": "npm run typecheck && npm test"
}
}
This arrangement provides two independent validation stages.
Type checking verifies the static correctness of TypeScript code.
Jest execution verifies runtime behavior through test cases.
A successful test run does not imply that the code is type-safe. Conversely, successful type checking does not imply that the implementation behaves correctly.
Keeping the two stages separate preserves the performance advantage of SWC while maintaining TypeScript’s static guarantees.
TypeScript projects often contain path aliases, custom module resolution, and compiler options that influence how source files are interpreted.
It is important to understand that SWC does not automatically implement every option in tsconfig.json.
For example, TypeScript may define aliases:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
],
"@tests/*": [
"tests/*"
]
}
}
}
This permits imports such as:
import { formatPrice } from "@/utils/format";
The TypeScript compiler understands the alias during type checking, but Jest must independently resolve the import at runtime.
The Jest configuration can map the alias:
module.exports = {
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
"^@tests/(.*)$": "<rootDir>/tests/$1"
},
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
}
};
The moduleNameMapper property controls Jest’s module resolution.
This distinction prevents a common configuration error: a path alias works in the editor and passes TypeScript checking but fails during Jest execution.
Other TypeScript compiler options may also have runtime implications.
Examples include:
baseUrl and paths, which affect module resolution.experimentalDecorators, which relates to decorator syntax.emitDecoratorMetadata, which affects generated metadata.jsx, which determines JSX handling in TypeScript.verbatimModuleSyntax, which influences TypeScript’s module semantics.These options should not be assumed to transfer automatically to SWC. Equivalent SWC settings or separate Jest configuration may be required.
Decorators are frequently used in frameworks that rely on classes, dependency injection, validation, or object-relational mapping.
SWC supports legacy TypeScript-style decorators through its transformation configuration.
A typical configuration is:
{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true
},
"transform": {
"legacyDecorator": true,
"decoratorMetadata": true
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
The settings have different purposes.
The parser option enables decorator syntax.
legacyDecorator enables transformation using legacy decorator semantics.
decoratorMetadata enables emission of metadata associated with decorated declarations, where supported by the configured transformation.
An example of a decorated class is:
function Component(
target: Function
): void {
Reflect.defineMetadata(
"component",
true,
target
);
}
@Component
export class UserService {
getName(): string {
return "User service";
}
}
This example uses the reflect-metadata library to store metadata.
The dependency must be installed separately:
npm install reflect-metadata
The metadata library must also be loaded before code that depends on its APIs:
import "reflect-metadata";
Decorator metadata is particularly sensitive to compiler configuration.
TypeScript’s emitDecoratorMetadata and SWC’s decoratorMetadata should not be treated as interchangeable implementations with identical behavior in every situation.
Frameworks that depend on reflected parameter types, constructor metadata, or specific decorator evaluation semantics may require additional compatibility testing.
Legacy decorators and the newer ECMAScript decorator model are distinct approaches. A project using one model cannot assume that code written for the other will behave identically.
The exact decorator semantics must match the framework and compiler configuration.
Module compatibility is one of the most important aspects of Jest configuration.
JavaScript supports different module systems, primarily:
Jest’s execution model and the SWC module output must be compatible.
In a traditional CommonJS Jest configuration, SWC converts imports and exports into CommonJS:
{
"module": {
"type": "commonjs"
}
}
A source module such as:
import { calculateTotal } from "./calculator";
export function calculateInvoice(
price: number,
quantity: number
): number {
return calculateTotal(price, quantity);
}
is transformed into CommonJS-compatible JavaScript.
This allows Jest to load the resulting module through its traditional module runtime.
However, modern Node.js projects increasingly use native ECMAScript modules.
A project using "type": "module" in package.json may need a different Jest configuration and a different SWC module strategy.
For an ESM-oriented project, SWC can preserve ES module syntax:
{
"jsc": {
"parser": {
"syntax": "typescript"
},
"target": "es2022"
},
"module": {
"type": "es6"
}
}
The Jest configuration must also be compatible with ESM execution.
For example, a project can use an ESM configuration file:
export default {
testEnvironment: "node",
extensionsToTreatAsEsm: [
".ts"
],
transform: {
"^.+\\.ts$": [
"@swc/jest",
{
jsc: {
parser: {
syntax: "typescript"
},
target: "es2022"
},
module: {
type: "es6"
}
}
]
}
};
Native ESM support in Jest has additional requirements that depend on the Jest and Node.js versions.
In particular, ESM execution may require enabling Jest’s VM module support through the appropriate Node.js runtime configuration for the installed Jest release.
The package configuration must also be consistent:
{
"type": "module",
"scripts": {
"test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js"
}
}
The --experimental-vm-modules option is relevant to Jest versions and Node.js execution modes that rely on this mechanism. Its necessity should be checked against the specific installed versions rather than assumed to be permanent.
The use of type: "module" does not automatically make every Jest configuration or test file ESM-compatible.
The module strategy should reflect the application architecture.
CommonJS is often simpler when:
ESM is preferable when:
Mixing incompatible module configurations often produces errors that appear unrelated to compilation.
Examples include Cannot use import statement outside a module, Unexpected token 'export', and failures involving require or import.
Such errors usually indicate a mismatch between the generated module format and the Jest runtime.
SWC does not change how Jest handles asynchronous tests.
The transformation layer compiles TypeScript and JavaScript syntax, while Jest continues to manage promises, asynchronous callbacks, and test completion.
Consider a service that retrieves a user:
type User = {
id: number;
name: string;
};
export async function getUser(
id: number
): Promise<User> {
const response = await fetch(
`https://example.com/users/${id}`
);
if (!response.ok) {
throw new Error("Unable to retrieve user");
}
return response.json() as Promise<User>;
}
A test can mock the global fetch implementation:
import { getUser } from "../src/services/userService";
describe("getUser", () => {
afterEach(() => {
jest.restoreAllMocks();
});
it("returns a user when the request succeeds", async () => {
jest.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
json: async () => ({
id: 1,
name: "Alex"
})
} as Response);
await expect(getUser(1)).resolves.toEqual({
id: 1,
name: "Alex"
});
});
it("throws when the request fails", async () => {
jest.spyOn(globalThis, "fetch").mockResolvedValue({
ok: false
} as Response);
await expect(getUser(1)).rejects.toThrow(
"Unable to retrieve user"
);
});
});
The example demonstrates that asynchronous execution is independent of SWC.
The transformer removes TypeScript annotations and converts the source code as configured. Jest then executes the asynchronous functions normally.
A subtle distinction is that the existence of fetch depends on the runtime environment. Modern Node.js releases provide a global fetch, but older runtimes may require a separate implementation or test mock.
SWC does not provide missing global APIs.
Jest supports module mocking through functions such as jest.mock, jest.fn, and jest.spyOn.
The availability and behavior of these facilities depend on the Jest module execution model.
In a CommonJS-oriented project, a module can be mocked as follows:
import { sendEmail } from "../src/services/emailService";
import { registerUser } from "../src/services/userService";
jest.mock("../src/services/emailService", () => ({
sendEmail: jest.fn()
}));
describe("registerUser", () => {
it("sends a welcome email", async () => {
await registerUser({
email: "user@example.com"
});
expect(sendEmail).toHaveBeenCalledWith(
"user@example.com",
"Welcome"
);
});
});
The mock replaces the email service implementation during the test.
The application module can therefore be tested without sending an actual email.
When using ESM, static imports are evaluated before ordinary test statements. Consequently, CommonJS-style mock hoisting assumptions do not apply in the same way.
Native ESM testing uses Jest’s ESM-specific module mocking facilities, including jest.unstable_mockModule in supported Jest versions, followed by dynamic import of the module under test.
For example:
import { jest } from "@jest/globals";
jest.unstable_mockModule(
"../src/services/emailService.js",
() => ({
sendEmail: jest.fn()
})
);
const { registerUser } = await import(
"../src/services/userService.js"
);
This approach is specific to Jest’s ESM support and its API stability should be checked for the installed release.
The important principle is that SWC does not redefine Jest’s module mocking semantics. The module format and Jest runtime determine which mocking approach is appropriate.
By default, Jest generally avoids transforming files inside node_modules.
This behavior improves performance because most installed packages already contain executable JavaScript.
However, some dependencies publish source code using syntax that the current Node.js runtime or Jest configuration cannot execute directly.
An example is a package that publishes untransformed ESM code.
A typical failure might look like:
Jest encountered an unexpected token
SyntaxError: Unexpected token 'export'
This can happen when a dependency contains ESM syntax but Jest attempts to execute it through a CommonJS-oriented path.
The transformIgnorePatterns option controls which files are excluded from transformation.
A selective configuration can be used:
module.exports = {
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
transformIgnorePatterns: [
"/node_modules/(?!(some-esm-package)/)"
]
};
In this example, some-esm-package is excluded from the normal ignore behavior and becomes eligible for transformation.
The package name is illustrative and should be replaced with the actual dependency.
For several packages:
module.exports = {
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
transformIgnorePatterns: [
"/node_modules/(?!(package-one|package-two|@scope/package-three)/)"
]
};
This approach should be applied selectively.
Transforming all of node_modules can substantially increase test startup time and memory consumption.
Some dependencies also rely on native ESM behavior, dynamic imports, or package-specific resolution rules. Simply passing their files through SWC does not guarantee compatibility.
The appropriate solution may involve:
Frontend applications frequently import CSS, SVG files, images, and other static resources.
SWC transforms JavaScript and TypeScript. It does not automatically transform arbitrary CSS or image files into JavaScript modules.
Jest therefore needs separate handling for these resources.
A typical configuration uses module mappings:
module.exports = {
testEnvironment: "jsdom",
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
moduleNameMapper: {
"\\.(css|less|scss)$": "<rootDir>/tests/mocks/styleMock.js",
"\\.(png|jpg|jpeg|gif|svg)$": "<rootDir>/tests/mocks/fileMock.js"
}
};
The CSS mock can be an empty module:
module.exports = {};
The file mock can export a placeholder:
module.exports = "test-file-stub";
These mappings prevent Jest from attempting to execute CSS and image files as JavaScript.
For CSS modules, a dedicated mock that preserves class-name access may be more appropriate:
module.exports = new Proxy(
{},
{
get: (_, property) => property
}
);
This allows tests to access CSS class names without loading actual stylesheets.
Static asset handling should reflect the needs of the test.
For most component tests, the actual image or stylesheet content is irrelevant. The purpose of the mock is to provide a predictable module interface.
Source maps connect generated JavaScript back to the original TypeScript or JavaScript source.
They are especially important when debugging test failures.
Without source maps, a stack trace may point to transformed code rather than the original source location.
SWC can generate source maps through its configuration:
{
"sourceMaps": true,
"jsc": {
"parser": {
"syntax": "typescript"
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
When using @swc/jest, source map handling is integrated with the transformer.
The transformer uses Jest’s transformation interface and returns the generated code with the corresponding source map when available.
Source maps improve:
A test that fails at runtime should ideally identify the original .ts or .tsx file and the corresponding source line.
Source maps do not eliminate every debugging complication. Complex transformations, generated code, decorators, and unusual module configurations can still produce stack traces that require additional interpretation.
Jest includes code coverage functionality.
Coverage measures which portions of the application were executed during a test run.
Typical metrics include:
A basic coverage configuration can be defined in jest.config.js:
module.exports = {
testEnvironment: "node",
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
collectCoverage: true,
collectCoverageFrom: [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts",
"!src/**/index.ts"
],
coverageDirectory: "coverage",
coverageReporters: [
"text",
"html",
"lcov"
]
};
The collectCoverageFrom option specifies the source files included in coverage collection.
Excluding declaration files is important because TypeScript declaration files do not contain executable statements.
The coverageDirectory property determines where reports are stored.
The reporters generate different output formats:
| Reporter | Purpose |
|---|---|
text |
Coverage summary in the terminal |
html |
Interactive HTML report |
lcov |
Machine-readable coverage information |
Jest supports different approaches to coverage instrumentation.
The traditional approach uses Babel-based instrumentation. SWC-based instrumentation can also be used through SWC’s coverage support, depending on the installed Jest and @swc/jest versions.
The @swc/jest transformer can be configured to instrument code:
module.exports = {
transform: {
"^.+\\.(t|j)sx?$": [
"@swc/jest",
{
jsc: {
parser: {
syntax: "typescript"
},
target: "es2022"
},
module: {
type: "commonjs"
},
sourceMaps: true
}
]
},
coverageProvider: "v8"
};
The v8 coverage provider uses runtime coverage information supplied by the JavaScript engine.
It is generally a convenient choice for modern Node.js environments.
Jest also supports a babel coverage provider, which relies on Babel-based instrumentation even when SWC is used for ordinary source transformation.
The choice of provider should be made deliberately.
V8 coverage measures execution using runtime information. Babel coverage uses instrumented code.
The resulting reports may differ in how they represent branches, generated constructs, and transformed expressions.
Coverage numbers are therefore not always directly comparable across providers.
Coverage collection also introduces additional overhead. Large test suites may execute noticeably slower when instrumentation is enabled.
Coverage thresholds define minimum acceptable coverage levels.
For example:
module.exports = {
collectCoverage: true,
coverageThreshold: {
global: {
branches: 75,
functions: 80,
lines: 85,
statements: 85
}
}
};
The thresholds represent minimum percentages.
If the collected coverage falls below one of the configured limits, Jest reports the failure and returns a nonzero exit status.
Thresholds can also be defined for individual files or directories:
module.exports = {
coverageThreshold: {
global: {
lines: 80
},
"./src/services/": {
branches: 85,
functions: 90,
lines: 90,
statements: 90
}
}
};
This makes it possible to enforce stronger requirements for critical business logic while maintaining a more moderate global threshold.
Coverage thresholds should not be interpreted as a direct measure of software quality.
High coverage does not guarantee meaningful assertions, correct edge-case handling, or reliable integration behavior.
Jest environments determine the globals and runtime facilities available to test files.
The two common environments are:
Node environment
Suitable for:
jsdom environment
Suitable for:
A project can select an environment globally:
module.exports = {
testEnvironment: "node"
};
Individual test files can override the environment with a docblock:
/**
* @jest-environment jsdom
*/
describe("DOM environment", () => {
it("provides a document object", () => {
expect(document).toBeDefined();
});
});
This is useful for applications that contain both backend and frontend code.
The environment does not influence SWC’s fundamental role. SWC still transforms source files before Jest executes them.
The environment only changes the runtime context.
Jest supports setup files that execute before tests.
Two important configuration options are setupFiles and setupFilesAfterEnv.
setupFiles runs before the Jest testing framework is installed in the test environment.
setupFilesAfterEnv runs after the testing framework has been installed.
The distinction matters when registering custom matchers, hooks, or test lifecycle behavior.
A configuration can look like this:
module.exports = {
testEnvironment: "jsdom",
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
setupFiles: [
"<rootDir>/tests/polyfills.ts"
],
setupFilesAfterEnv: [
"<rootDir>/tests/setup.ts"
]
};
The polyfill file can initialize missing runtime functionality:
import "whatwg-fetch";
The package must be installed separately if this polyfill is required.
The test setup file can register additional matchers and lifecycle hooks:
import "@testing-library/jest-dom";
beforeEach(() => {
jest.clearAllMocks();
});
The setup file is executed within the test environment.
It is therefore suitable for common initialization that must be repeated across test files.
A distinction exists between clearing, resetting, and restoring mocks:
jest.clearAllMocks() clears call history and recorded results.jest.resetAllMocks() resets mock state and mock implementations.jest.restoreAllMocks() restores original implementations for spies and other restorable mocks.The correct choice depends on whether test isolation requires preserving mock implementations.
Large applications often use a monorepository containing multiple packages.
For example:
monorepo/
├── apps/
│ ├── web/
│ └── api/
├── packages/
│ ├── shared/
│ ├── ui/
│ └── config/
├── package.json
└── jest.config.js
Each package may have its own Jest configuration, or a root configuration may coordinate multiple projects.
Jest provides the projects configuration property for this purpose.
A root configuration can define multiple projects:
module.exports = {
projects: [
"<rootDir>/apps/web/jest.config.js",
"<rootDir>/apps/api/jest.config.js",
"<rootDir>/packages/shared/jest.config.js"
]
};
Each project can use its own SWC settings.
For example, the web project may require TSX parsing and jsdom, while the API project may use TypeScript without JSX and the Node environment.
A web configuration:
module.exports = {
displayName: "web",
rootDir: ".",
testEnvironment: "jsdom",
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
}
};
An API configuration:
module.exports = {
displayName: "api",
rootDir: ".",
testEnvironment: "node",
transform: {
"^.+\\.ts$": "@swc/jest"
}
};
A shared package may have its own configuration that includes both JavaScript and TypeScript.
The key architectural consideration is consistency.
Shared packages should be transformed in a way that reflects their published source format and the runtime expectations of consuming packages.
If a shared package is imported through source files, Jest may need to transform it. If it is imported through compiled distribution files, the test configuration may be able to execute those files directly.
Transforming source files consumes CPU resources.
Jest therefore uses caching to avoid repeatedly transforming unchanged files.
The cache can significantly reduce execution time during development.
The behavior depends on factors such as:
A change in SWC options may invalidate cached transformations because the output depends on the configuration.
Jest normally manages its cache automatically.
The cache location can be inspected using:
npx jest --showConfig
The cache can be cleared manually:
npx jest --clearCache
Clearing the cache is useful when debugging unexpected transformation behavior.
It should not be part of every normal test run because it removes reusable compiled output and increases subsequent startup time.
The first test run may be slower because Jest needs to transform the source files.
Subsequent runs can reuse cached results.
For a large TypeScript project, the difference can be substantial.
The cache is particularly beneficial when:
In continuous integration environments, caching should be configured carefully.
A cache key should account for relevant dependencies and configuration files. Reusing an incompatible cache can produce confusing results or unnecessary cache invalidation.
Jest watch mode monitors project files and reruns affected tests.
SWC works within this workflow without requiring a separate compiler process.
The standard command is:
npx jest --watch
Jest analyzes changes and selects relevant tests based on its dependency graph.
A related command is:
npx jest --watchAll
The difference is that --watchAll continuously monitors and runs the entire test suite rather than relying primarily on affected-test selection.
For a large project, ordinary watch mode is usually more efficient.
The transformation cache also helps reduce repeated SWC compilation.
A development workflow can combine type checking, testing, and production compilation:
{
"scripts": {
"dev": "jest --watch",
"test": "jest",
"test:ci": "jest --ci --coverage",
"typecheck": "tsc --noEmit",
"build": "swc src -d dist"
}
}
The exact production build command depends on the SWC CLI installation and build configuration.
The important distinction is that the test transformation and production build are separate processes.
A successful Jest transformation does not automatically verify the complete production build pipeline.
SWC supports plugins that extend its transformation capabilities.
Plugins can implement additional syntax transformations or modify compiler behavior.
For example, a project may use a plugin to transform a framework-specific syntax extension.
The plugin must be compatible with the installed SWC version and platform.
A plugin can be configured in .swcrc:
{
"jsc": {
"experimental": {
"plugins": [
[
"plugin-package-name",
{
"option": true
}
]
]
},
"parser": {
"syntax": "typescript"
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
The package name and options in this example are placeholders.
The experimental.plugins configuration should be treated as version-sensitive because SWC plugin interfaces and compatibility requirements can evolve.
A plugin that works during a production build may not automatically work in Jest.
Potential reasons include:
For predictable behavior, test and production transformations should use compatible plugin versions and equivalent relevant settings.
Some applications require different compilation settings for development, production, and testing.
A single .swcrc is sufficient for many projects, but separate configurations can be useful when the environments have materially different requirements.
For example, a production build may preserve ESM syntax, while Jest may require CommonJS output.
A dedicated test configuration can be stored in .swcrc.test:
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"transform": {
"react": {
"runtime": "automatic"
}
},
"target": "es2022"
},
"module": {
"type": "commonjs"
},
"sourceMaps": true
}
The Jest configuration can supply these settings explicitly:
const fs = require("node:fs");
const path = require("node:path");
const swcOptions = JSON.parse(
fs.readFileSync(
path.join(__dirname, ".swcrc.test"),
"utf8"
)
);
module.exports = {
testEnvironment: "node",
transform: {
"^.+\\.(t|j)sx?$": [
"@swc/jest",
swcOptions
]
}
};
This approach makes test-specific transformation behavior explicit.
It is particularly useful when the production compiler preserves ES modules but the Jest runtime uses CommonJS.
However, duplicated configuration introduces maintenance overhead.
If a parser option or transformation setting changes in the production build, the test configuration may need a corresponding update.
The trade-off is between configuration isolation and configuration consistency.
Continuous integration systems execute tests in clean or partially cached environments.
A reliable CI configuration should distinguish test execution, type checking, and coverage collection.
A basic workflow can be expressed through package scripts:
{
"scripts": {
"typecheck": "tsc --noEmit",
"test": "jest",
"test:ci": "jest --ci --coverage",
"validate": "npm run typecheck && npm run test:ci"
}
}
The --ci flag tells Jest that it is running in a continuous integration environment.
This can affect snapshot behavior and other CI-specific execution decisions.
The coverage output can be consumed by additional reporting systems.
A CI pipeline should also use a deterministic dependency installation strategy, such as:
npm ci
npm run validate
npm ci installs dependencies according to the lockfile and is intended for automated environments.
This helps ensure that the versions of Jest, SWC, and their related packages are consistent between local development and CI.
Jest snapshot testing records serialized representations of values or rendered output.
SWC does not change the fundamental snapshot mechanism.
A component test may look like this:
import { render } from "@testing-library/react";
import { Button } from "../src/components/Button";
describe("Button snapshots", () => {
it("matches the saved snapshot", () => {
const { asFragment } = render(
<Button label="Continue" />
);
expect(asFragment()).toMatchSnapshot();
});
});
Jest creates or compares the snapshot.
The SWC transformer only compiles the component and test code before execution.
Snapshots are most useful for stable output structures. Large snapshots that change frequently can make reviews difficult and may conceal meaningful differences.
Historically, Babel has been a common transformation layer for Jest.
The babel-jest package integrates Babel with Jest, while @swc/jest provides an equivalent role using SWC.
Both tools can transform modern JavaScript and TypeScript-related syntax, although their configuration models and supported transformations differ.
| Characteristic | babel-jest |
@swc/jest |
|---|---|---|
| Compiler | Babel | SWC |
| Implementation | JavaScript | Rust-based compiler |
| TypeScript syntax removal | Supported through configuration | Supported |
| JSX transformation | Supported | Supported |
| Plugin ecosystem | Extensive Babel ecosystem | SWC plugin ecosystem |
| Transformation speed | Depends on configuration and project | Often faster on large projects |
| Jest integration | Direct transformer | Direct transformer |
| Type checking | Not performed by Babel | Not performed by SWC |
The most important practical difference is often performance.
SWC is designed for high-speed compilation and can significantly reduce transformation overhead in large projects.
However, the speed advantage depends on the source code, configuration, cache behavior, and transformations required.
Babel may remain necessary when a project relies on a Babel plugin without an equivalent SWC transformation.
The migration from babel-jest to @swc/jest is therefore not always a simple package replacement.
A Babel-based Jest configuration might look like this:
module.exports = {
transform: {
"^.+\\.[jt]sx?$": "babel-jest"
}
};
The corresponding Babel configuration could contain:
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript",
"@babel/preset-react"
]
}
A basic SWC replacement can use:
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"transform": {
"react": {
"runtime": "automatic"
}
},
"target": "es2022"
},
"module": {
"type": "commonjs"
}
}
The Jest transformer can then be changed:
module.exports = {
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
}
};
A migration should account for more than syntax parsing.
The following areas deserve particular attention:
Babel and SWC do not guarantee identical output for every combination of options.
Tests that pass after a basic migration do not necessarily establish complete behavioral equivalence.
The principal reason for integrating SWC with Jest is often transformation speed.
In a large TypeScript project, test execution may involve thousands of source files.
Each file may need parsing, syntax transformation, module conversion, and source map generation.
A compiler implemented in Rust can perform these operations efficiently.
However, total Jest execution time is not determined exclusively by the compiler.
A simplified performance model is:
[ T_{} = T_{} + T_{} + T_{} + T_{} + T_{} ]
Where:
SWC primarily improves the transformation component.
If a project spends most of its time executing integration tests, making transformation faster may produce only a modest overall improvement.
For example, suppose transformation consumes 40% of the original test runtime and becomes four times faster.
The theoretical overall speedup, assuming all other costs remain unchanged, is:
[ S = ]
Where:
For (p=0.4) and (k=4):
[ S = ]
[ S ]
The total test suite becomes approximately 1.43 times faster rather than four times faster.
This illustrates why performance measurements should distinguish compilation time from test execution time.
Several configuration choices influence SWC performance.
Use an appropriate target.
A modern Node.js target avoids unnecessary transformations for syntax already supported by the runtime.
Avoid unnecessary plugins.
Every additional transformation can introduce processing overhead.
Limit dependency transformation.
Only dependencies that require compilation should normally be transformed.
Use caching.
Jest’s transformation cache reduces repeated work.
Avoid redundant compilation.
Running a separate TypeScript emission step before Jest is unnecessary when @swc/jest already performs the required syntax transformation.
Separate type checking.
Type checking can run as an independent process or CI stage.
Avoid unnecessary source map work in environments where it is not required.
Source maps are valuable during development and debugging, but their overhead should be considered in large test environments.
Several errors occur frequently when configuring Jest with SWC.
A typical error is:
SyntaxError: Unexpected token ':'
This often indicates that the file was not transformed or that the parser is configured for ordinary JavaScript rather than TypeScript.
The parser should use:
{
"jsc": {
"parser": {
"syntax": "typescript"
}
}
}
The Jest transform pattern must also match the file extension.
An error involving JSX syntax may indicate that JSX support is disabled.
For TypeScript React components, the parser should include:
{
"parser": {
"syntax": "typescript",
"tsx": true
}
}
The React transformation should also be configured when JSX needs to be converted into executable JavaScript.
An error such as:
SyntaxError: Unexpected token 'export'
often indicates that Jest is trying to execute ESM output in a CommonJS context or is encountering an untransformed dependency.
The module format should be checked:
{
"module": {
"type": "commonjs"
}
}
For native ESM projects, the Jest runtime should instead be configured consistently with ESM output.
This error usually indicates that ES module syntax reached a runtime path expecting CommonJS.
Possible causes include:
The solution is to align the module output format with the Jest execution model.
If TypeScript recognizes an alias but Jest cannot load it, the problem is usually module resolution rather than transformation.
A corresponding moduleNameMapper entry is required.
For example:
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1"
}
If a dependency injection framework cannot discover parameter types, the SWC configuration may be missing the appropriate decorator settings.
The relevant configuration includes:
{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true
},
"transform": {
"legacyDecorator": true,
"decoratorMetadata": true
}
}
}
The metadata runtime dependency and initialization order must also be correct.
This behavior is expected when SWC is used without a separate type-checking stage.
SWC removes TypeScript syntax but does not perform complete static type analysis.
Running the TypeScript compiler separately resolves this gap:
npx tsc --noEmit
Jest may be using previously transformed files from its cache.
Clearing the cache can help isolate the problem:
npx jest --clearCache
Configuration file discovery should also be checked. An unexpected .swcrc, Jest configuration, or environment-specific configuration can cause the transformer to use different settings from those intended.
The following example combines the principal elements of a typical SWC-powered Jest setup.
The package configuration:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"typecheck": "tsc --noEmit",
"validate": "npm run typecheck && npm test"
},
"devDependencies": {
"@swc/core": "^1.0.0",
"@swc/jest": "^0.2.0",
"@types/jest": "^30.0.0",
"@testing-library/jest-dom": "^6.0.0",
"@testing-library/react": "^16.0.0",
"jest": "^30.0.0",
"jest-environment-jsdom": "^30.0.0",
"typescript": "^5.0.0"
}
}
The version ranges illustrate the package relationships rather than prescribing a complete compatible lockfile. Actual versions should be selected and locked together according to their published compatibility requirements.
The SWC configuration:
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"transform": {
"react": {
"runtime": "automatic"
}
},
"target": "es2022"
},
"module": {
"type": "commonjs"
},
"sourceMaps": true
}
The Jest configuration:
module.exports = {
testEnvironment: "jsdom",
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest"
},
testMatch: [
"**/?(*.)+(spec|test).[tj]s?(x)"
],
setupFilesAfterEnv: [
"<rootDir>/tests/setup.ts"
],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
"\\.(css|less|scss)$":
"<rootDir>/tests/mocks/styleMock.js",
"\\.(png|jpg|jpeg|svg)$":
"<rootDir>/tests/mocks/fileMock.js"
},
collectCoverageFrom: [
"src/**/*.{ts,tsx}",
"!src/**/*.d.ts"
],
coverageDirectory: "coverage",
coverageReporters: [
"text",
"html",
"lcov"
],
coverageProvider: "v8",
clearMocks: true
};
The TypeScript configuration:
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"jsx": "react-jsx",
"types": [
"jest",
"node"
]
},
"include": [
"src",
"tests"
]
}
The test setup file:
import "@testing-library/jest-dom";
The style mock:
module.exports = {};
The static file mock:
module.exports = "test-file-stub";
This configuration establishes a clear division of responsibilities:
The result is a testing environment that uses the same general compiler technology as the rest of the application while preserving Jest’s established testing capabilities.
The integration of SWC and Jest is most effective when compilation and testing responsibilities remain clearly separated.
SWC should handle syntax parsing, transformation, and the generation of executable JavaScript.
Jest should handle test discovery, execution, isolation, assertions, mocks, snapshots, and coverage reporting.
TypeScript should remain responsible for static type checking when TypeScript is used.
The runtime environment should provide the APIs expected by the application, including Node.js facilities or browser-like APIs supplied through jsdom.
Module resolution should remain consistent across TypeScript, SWC, Jest, and the production build system.
A particularly important consideration is that test compilation is not necessarily production compilation. Different module formats, targets, plugins, and environment assumptions can cause the same source file to behave differently in the two environments.
A well-maintained configuration minimizes these differences while allowing the test runner to use the module format and execution model it supports.
For projects already using SWC, @swc/jest provides a direct integration without introducing Babel as an additional transformation layer. It offers fast TypeScript and JSX transformation, integrates with Jest’s caching mechanism, supports source maps, and accommodates a wide range of modern JavaScript project structures. Its effectiveness depends on correctly aligning parser options, module output, runtime capabilities, dependency transformation, and independent type-checking requirements.