Back to Repositories

Testing Binary Bit Manipulation Operations in javascript-algorithms

A comprehensive test suite for validating bit manipulation functionality in JavaScript, specifically testing the updateBit operation that modifies individual bits at specified positions in binary numbers. The tests cover both setting and clearing bits across different numeric values.

Test Coverage Overview

The test suite provides thorough coverage of the updateBit function’s capabilities.

Key areas tested include:
  • Setting bits to 1 at various positions
  • Clearing bits to 0 at specific positions
  • Testing different base numbers (1 and 10)
  • Verifying operations across multiple bit positions

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern for structured test organization. Individual test cases use expect().toBe() assertions to verify exact numeric outcomes of bit operations. Binary number representations (0b0001, 0b1010) are used as reference points in comments for clarity.

Technical Details

Testing infrastructure:
  • Jest testing framework
  • Binary number manipulation
  • Direct numeric comparisons
  • Isolated unit tests
Test configuration focuses on precise numeric equality checks for bit manipulation outcomes.

Best Practices Demonstrated

The test suite exemplifies several testing best practices.

Notable elements include:
  • Clear test case organization
  • Comprehensive edge case coverage
  • Binary number documentation
  • Consistent assertion patterns
  • Focused test scope

trekhleb/javascript-algorithms

src/algorithms/math/bits/__test__/updateBit.test.js

            
import updateBit from '../updateBit';

describe('updateBit', () => {
  it('should update bit at specific position', () => {
    // 1 = 0b0001
    expect(updateBit(1, 0, 1)).toBe(1);
    expect(updateBit(1, 0, 0)).toBe(0);
    expect(updateBit(1, 1, 1)).toBe(3);
    expect(updateBit(1, 2, 1)).toBe(5);

    // 10 = 0b1010
    expect(updateBit(10, 0, 1)).toBe(11);
    expect(updateBit(10, 0, 0)).toBe(10);
    expect(updateBit(10, 1, 1)).toBe(10);
    expect(updateBit(10, 1, 0)).toBe(8);
    expect(updateBit(10, 2, 1)).toBe(14);
    expect(updateBit(10, 2, 0)).toBe(10);
  });
});