Skip to content

Instantly share code, notes, and snippets.

@codewithleader
Last active June 20, 2024 20:50
Show Gist options
  • Save codewithleader/48dc73abb5f9f29f93589d2b89cae790 to your computer and use it in GitHub Desktop.
Save codewithleader/48dc73abb5f9f29f93589d2b89cae790 to your computer and use it in GitHub Desktop.
Pasos para configurar NodeJS con Jest para pruebas

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

Respuestas al jest -init:

  • √ Would you like to use Jest when running "test" script in "package.json"? ... yes
  • √ Would you like to use Typescript for the configuration file? ... yes
  • √ Choose the test environment that will be used for testing » node
  • √ Do you want Jest to add coverage reports? ... yes
  • √ Which provider should be used to instrument code for coverage? » v8
  • √ Automatically clear mock calls, instances, contexts and results before every test? ... yes
  1. En el archivo jest.config.ts 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'],
setupFiles: ['<rootDir>/.jest/set-env-vars.ts'],
  1. Crear archivo set-env-varts.ts en la carpeta .jest/
import { config } from 'dotenv'; // `npm i -D dotenv`
import { resolve } from 'path';

// Cargar variables de entorno desde .env.test
config({ path: resolve(__dirname, '../.env.test') });
  1. Crear scripts en el package.json
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment