Skip to content

Instantly share code, notes, and snippets.

@Klerith
Created August 19, 2023 18:35
Show Gist options
  • Select an option

  • Save Klerith/98d7b1bc0f1525e892f260813cad1007 to your computer and use it in GitHub Desktop.

Select an option

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",
@jlcarrascof
Copy link
Copy Markdown

Si el app.test.ts te muestra errores en describe, test y expect ....

En el tsconfig.json, se corrige colocando esta linea:

"types": ["node", "jest"],

Usualmente los valores por defecto son: "types": ["node"],

Si tienen algún feedback, lo dejan por acá ....

Gracias Fernando, por tan valioso material.

@jdomingu19
Copy link
Copy Markdown

Solución: Configuración Jest + TypeScript (2026)

Comandos iniciales para la instalación:

npm install -D jest @types/jest ts-jest supertest
npx create-jest

Establece "type": "module" en el package.json para poder ejecutar npm run test sin errores en la terminal. Estos son los valores clave del package.json necesarios para el correcto funcionamiento de los tests en la Clase 55:

{
  "name": "06-testing-introduction",
  ...
  "type": "module",
  ...
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    ...
  },
  "devDependencies": {
    "@types/jest": "^30.0.0",
    ...
    "jest": "^30.3.0",
    ...
    ...
    "supertest": "^7.2.2",
    "ts-jest": "^29.4.9",
    "ts-node": "^10.9.2",
    "typescript": "^6.0.2"
  },
  ...
}

Estas configuraciones corresponden al estado del curso hasta la Clase 55. Es recomendable comentar todas las opciones por defecto generadas con tsc --init, destacando especialmente "rootDir": "src" (elimínalo), ya que este ajuste permite que los scripts de testing ubicados en la carpeta tests/ funcionen correctamente.

image

Configuraciones del archivo tsconfig.ts

image

Correcto funcionamiento de Jest y TypeScript con npm run test

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