Skip to main content

Testing

Unit testing is fundamental to software quality. Here's how different languages handle testing with their built-in or most popular frameworks.

Basic Unit Tests​

// 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 & Advanced Testing​

// 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');
});

Key Takeaways​

  • Built-in vs external frameworks -- Rust, Go, and Zig ship with test runners; JavaScript, Python, PHP, and C++ rely on external tools (Jest, pytest, PHPUnit, Google Test).
  • Assertion styles differ -- Go uses manual if got != want { t.Errorf(...) }; xUnit/Jest use Assert.Equal/expect().toBe; RSpec and FluentAssertions favor BDD-style expect(x).to eq(y).
  • Mocking approaches vary -- Interface-based mocking is common in Go and Swift; Java/C# use Mockito/Moq; Python uses unittest.mock; Rust uses crates like mockall with trait-based mocks.
  • Parameterized tests are idiomatic in some ecosystems -- Go favors table-driven tests; xUnit uses [Theory] and [InlineData]; JUnit 5 and Swift Testing have @ParameterizedTest and @Test(arguments:).
  • Performance testing is built-in for Go -- go test -bench=. runs benchmarks; other languages typically use separate tools (pytest-benchmark, criterion for Rust, etc.).