Skip to content

Instantly share code, notes, and snippets.

@slavafomin
Last active January 3, 2024 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slavafomin/9d97c9794a3ce4293722b83aeaa05e4c to your computer and use it in GitHub Desktop.
Save slavafomin/9d97c9794a3ce4293722b83aeaa05e4c to your computer and use it in GitHub Desktop.
Using Jest with SWC, TypeScript, and ESM

Using Jest with SWC, TypeScript, and ESM

Install dependencies

pnpm add -D jest @jest/globals @types/jest @swc/jest

Create jest.config.js file

/** @type {import('jest').Config} */
const config = {
  testMatch: [
    '<rootDir>/src/**/*.test.ts',
  ],
  moduleFileExtensions: [
    'js', 'ts',
  ],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.jsx?$': '$1',
  },
  transform: {
    '^.+\\.tsx?$': ['@swc/jest', {
      // Your SWC config here
    }],
  },
};

export default config;

Write your tests

import { describe, it, expect } from '@jest/globals';

import { greet } from './greet.js';


describe('encodeTlData()', () => {

  it('works', () => {

    expect(
      greet('John')
      
    ).toEqual('Hello John!');

  });

});

Notes

  • SWC doesn't support tsconfig.json, therefore it's lacking from the configuration.

  • Why not jest.config.ts? Jest requires ts-node to read config in TS format, however, the ts-node is no longer maintained and doesn't support various new features like multiple extends in tsconfig.json. We also like to keep our dependencies minimal.

  • SWC is very fast but doesn't type-check! So make sure to check your types inside your IDE or using TypeScript compiler. Always check your types as part of CI/CD (before running tests)!

Was this helpful?

Please add a star. Also, join my Telegram channel for more useful guides and insights on JavaScript/TypeScript development.

Have questions/feedback?

Be my guest to comment in the section below or under posts in my Telegram channel.

Need professional consultancy? You can contact me directly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment