Saltar al contenido principal

Testing

Las pruebas unitarias son fundamentales para la calidad del software. Así es como los diferentes lenguajes manejan las pruebas con sus frameworks integrados o más populares.

Pruebas Unitarias Básicas​

// Jest (most popular)
// npm install --save-dev jest

// math.js
function add(a, b) { return a + b; }
module.exports = { add };

// math.test.js
const { add } = require('./math');

describe('add', () => {
test('adds two numbers', () => {
expect(add(1, 2)).toBe(3);
});

test('handles negative numbers', () => {
expect(add(-1, 1)).toBe(0);
});

test('handles zero', () => {
expect(add(0, 0)).toBe(0);
});
});

// Run: npx jest

Mocking y Pruebas Avanzadas​

// Jest mocking
jest.mock('./api');
const api = require('./api');

api.fetchUser.mockResolvedValue({ name: 'John' });

test('fetches user', async () => {
const user = await getUser(1);
expect(api.fetchUser).toHaveBeenCalledWith(1);
expect(user.name).toBe('John');
});

// Spies
const spy = jest.spyOn(console, 'log');
doSomething();
expect(spy).toHaveBeenCalledWith('expected');

// Async testing
test('async operation', async () => {
await expect(fetchData()).resolves.toBe('data');
await expect(failOp()).rejects.toThrow('error');
});

Puntos Clave​

  • Frameworks integrados vs externos -- Rust, Go y Zig incluyen ejecutores de pruebas integrados; JavaScript, Python, PHP y C++ dependen de herramientas externas (Jest, pytest, PHPUnit, Google Test).
  • Los estilos de aserción difieren -- Go usa if got != want { t.Errorf(...) } manual; xUnit/Jest usan Assert.Equal/expect().toBe; RSpec y FluentAssertions favorecen el estilo BDD expect(x).to eq(y).
  • Los enfoques de mocking varían -- El mocking basado en interfaces es común en Go y Swift; Java/C# usan Mockito/Moq; Python usa unittest.mock; Rust usa crates como mockall con mocks basados en traits.
  • Las pruebas parametrizadas son idiomáticas en algunos ecosistemas -- Go favorece las pruebas dirigidas por tablas; xUnit usa [Theory] e [InlineData]; JUnit 5 y Swift Testing tienen @ParameterizedTest y @Test(arguments:).
  • Las pruebas de rendimiento están integradas en Go -- go test -bench=. ejecuta benchmarks; otros lenguajes típicamente usan herramientas separadas (pytest-benchmark, criterion para Rust, etc.).