Introduccion a Jest - Fundamentos de Pruebas en JavaScript

Intermedio | 50 min de lectura | 2024.12.23

Lo que Aprenderas en este Tutorial

✓ Configuracion de Jest
✓ Escribir pruebas basicas
✓ Matchers (aserciones)
✓ Mocks y spies
✓ Pruebas asincronas
✓ Reportes de cobertura

Step 1: Configuracion

npm init -y
npm install -D jest @types/jest ts-jest typescript
npx ts-jest config:init

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*.test.ts'],
  collectCoverageFrom: ['src/**/*.ts'],
};

Step 2: Pruebas Basicas

// src/math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export function divide(a: number, b: number): number {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

// src/math.test.ts
import { add, divide } from './math';

describe('Math functions', () => {
  describe('add', () => {
    it('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });

    it('should handle negative numbers', () => {
      expect(add(-1, 1)).toBe(0);
    });
  });

  describe('divide', () => {
    it('should divide two numbers', () => {
      expect(divide(10, 2)).toBe(5);
    });

    it('should throw error for division by zero', () => {
      expect(() => divide(10, 0)).toThrow('Division by zero');
    });
  });
});

Step 3: Matchers

// Igualdad
expect(value).toBe(3);           // Igualdad estricta
expect(obj).toEqual({ a: 1 });   // Comparacion de objetos

// Valores booleanos
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeDefined();

// Numeros
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThanOrEqual(5);
expect(0.1 + 0.2).toBeCloseTo(0.3);

// Cadenas
expect(str).toMatch(/pattern/);
expect(str).toContain('substring');

// Arrays
expect(arr).toContain(item);
expect(arr).toHaveLength(3);

Step 4: Mocks

// src/userService.ts
import { db } from './db';

export async function getUser(id: number) {
  return db.user.findById(id);
}

// src/userService.test.ts
import { getUser } from './userService';
import { db } from './db';

jest.mock('./db');

describe('UserService', () => {
  it('should return user', async () => {
    const mockUser = { id: 1, name: 'Test' };
    (db.user.findById as jest.Mock).mockResolvedValue(mockUser);

    const result = await getUser(1);
    expect(result).toEqual(mockUser);
    expect(db.user.findById).toHaveBeenCalledWith(1);
  });
});

Step 5: Pruebas Asincronas

// async/await
it('should fetch data', async () => {
  const data = await fetchData();
  expect(data).toBeDefined();
});

// Promises
it('should resolve', () => {
  return expect(asyncFunc()).resolves.toBe('value');
});

it('should reject', () => {
  return expect(asyncFunc()).rejects.toThrow();
});

Step 6: Ejecucion de Pruebas

# Ejecutar pruebas
npm test

# Modo watch
npm test -- --watch

# Cobertura
npm test -- --coverage

Resumen

Jest es un framework de pruebas facil de usar con funciones de mock completas. Escribir pruebas mejora la calidad y confiabilidad del codigo.

← Volver a la lista