✨ Testing

Unit Testing Best Practices

Last updated: 2025-09-25 02:29:54

Unit Testing Fundamentals

Unit testing ensures individual components work correctly in isolation.

JavaScript Testing with Jest

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

function multiply(a, b) {
  return a * b;
}

module.exports = { add, multiply };

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

describe('Math functions', () => {
  test('adds 1 + 2 to equal 3', () => {
    expect(add(1, 2)).toBe(3);
  });
  
  test('multiplies 3 * 4 to equal 12', () => {
    expect(multiply(3, 4)).toBe(12);
  });
  
  test('handles zero values', () => {
    expect(add(0, 5)).toBe(5);
    expect(multiply(0, 5)).toBe(0);
  });
});

React Component Testing

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';

describe('Counter Component', () => {
  test('renders initial count', () => {
    render();
    expect(screen.getByText('Count: 0')).toBeInTheDocument();
  });
  
  test('increments count when button clicked', () => {
    render();
    const button = screen.getByRole('button', { name: /increment/i });
    
    fireEvent.click(button);
    
    expect(screen.getByText('Count: 1')).toBeInTheDocument();
  });
  
  test('displays custom initial count', () => {
    render();
    expect(screen.getByText('Count: 5')).toBeInTheDocument();
  });
});

PHP Unit Testing with PHPUnit

<?php
// Calculator.php
class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }
    
    public function divide($a, $b) {
        if ($b === 0) {
            throw new InvalidArgumentException('Division by zero');
        }
        return $a / $b;
    }
}

// CalculatorTest.php
use PHPUnit\Framework\TestCase;

class CalculatorTest extends TestCase {
    private $calculator;
    
    protected function setUp(): void {
        $this->calculator = new Calculator();
    }
    
    public function testAdd() {
        $result = $this->calculator->add(2, 3);
        $this->assertEquals(5, $result);
    }
    
    public function testDivide() {
        $result = $this->calculator->divide(10, 2);
        $this->assertEquals(5, $result);
    }
    
    public function testDivideByZero() {
        $this->expectException(InvalidArgumentException::class);
        $this->calculator->divide(10, 0);
    }
}
?>