Skip to content

Instantly share code, notes, and snippets.

@santoshshinde2012
Created May 29, 2024 10:14
Show Gist options
  • Save santoshshinde2012/02d8c8696aed13764383af036bed0df0 to your computer and use it in GitHub Desktop.
Save santoshshinde2012/02d8c8696aed13764383af036bed0df0 to your computer and use it in GitHub Desktop.
Setup jest for typescript project

Step 1: Installation

npm install --save-dev jest @types/jest ts-jest eslint-plugin-jest

Step 2: Configuration

  • We used the below configuration to configure jest, and in our case, we are using the jest.config.ts file.
import type { Config } from 'jest';

const config: Config = {
  verbose: true,
  preset: 'ts-jest',
  roots: [
    "./tests"
  ],
  coveragePathIgnorePatterns: [
    "/node_modules/",
    "/tests/"
  ],
  collectCoverage: true,
  testEnvironment: 'node'
};

export default config;
  • Also, we need to update the eslint configuration, for ESLint plugin for Jest
// eslint.config.mjs
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import jestPlugin from 'eslint-plugin-jest';
import prettierConfig from 'eslint-config-prettier';

export default tseslint.config(
  {
    // config with just ignores is the replacement for `.eslintignore`
    ignores: ['**/build/**', '**/dist/**', 'coverage', 'docker'],
  },

  // Turns off all rules that are unnecessary or might conflict with Prettier.
  prettierConfig,

  // recommended eslint config
  eslint.configs.recommended,

  // strict: a superset of recommended that includes more opinionated rules which may also catch bugs.
  ...tseslint.configs.strict,

  // stylistic: additional rules that enforce consistent styling without significantly catching bugs or changing logic.
  ...tseslint.configs.stylistic,

  // ESLint plugin for Jest
  {
    files: ['**/*.spec.ts'],
    ...jestPlugin.configs['flat/recommended']
  }
);

Step 3: Running Jest

  • Add below script in package.json
  "test": "jest --silent --coverage",
  "test:watch": "jest --watch",
  • Run Command
npm run test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment