Skip to content

Instantly share code, notes, and snippets.

@Klerith
Created August 19, 2023 18:35
Show Gist options
  • Save Klerith/98d7b1bc0f1525e892f260813cad1007 to your computer and use it in GitHub Desktop.
Save Klerith/98d7b1bc0f1525e892f260813cad1007 to your computer and use it in GitHub Desktop.
Note + TypeScript + Jest = Testing

Pasos para configurar Jest con TypeScript, en Node

Documentación oficial sobre Jest

  1. Instalaciones de desarrollo (super test es útil para probar Express)
npm install -D jest @types/jest ts-jest supertest
  1. Crear archivo de configuración de Jest
npx jest --init
  1. En el archivo jest.config.js configurar
preset: 'ts-jest',
testEnvironment: "jest-environment-node",

// Opcional - The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: ['dotenv/config'],
  1. Crear scripts en el package.json
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
@pleivac
Copy link

pleivac commented Jun 25, 2024

Workaround para el error:

Error: Jest: Failed to parse the TypeScript config file C:\Users\...\jest.config.ts
Error: Jest: 'ts-node' is required for the TypeScript configuration files. Make sure it is installed
Error: Cannot find package 'ts-node' imported from

Hacer la instalación de ts-node:

npm install -D ts-node

@cristianA123
Copy link

Captura de pantalla 2024-06-30 223211
Captura de pantalla 2024-06-30 223057

@AlejoDev95
Copy link

Dejo mi configuración para usar path aliases

import type { Config } from "jest";

const config: Config = {
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8",
  moduleNameMapper: {
    "^@src/(.*)$": "<rootDir>/src/$1",
  },
  preset: "ts-jest",
  testEnvironment: "jest-environment-node",
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  moduleFileExtensions: ["ts", "tsx", "js", "json"],
};

export default config;
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDir": ".",
    "baseUrl": ".",
    "paths": {
      "@src/*": ["src/*"]
    },
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*", "test/**/*"],
  "exclude": ["node_modules", "dist"]
}

Esto les permitira realizar importaciones como la siguiente

import { emailTemplate } from "@src/foundation/01_template";

describe("01_template", () => {
  it("should ", () => {
    const messageExpected = "Hi, ";
    expect(emailTemplate).toContain(messageExpected);
  });
});

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