Back to Repositories

Testing Power of Two Algorithm Implementation in javascript-algorithms

This test suite validates the isPowerOfTwo function implementation, which determines if a given number is a power of two. The tests systematically verify the function’s ability to identify numbers that can be expressed as 2^n, covering both positive and negative test cases.

Test Coverage Overview

The test suite provides comprehensive coverage for the isPowerOfTwo function, examining a wide range of input values.

Key test cases include:
  • Positive powers of two (1, 2, 4, 8, 16, 64, 1024)
  • Non-powers of two (3, 5, 6, 7, 10, 12, 31, 1023)
  • Edge cases (0, -1)

Implementation Analysis

The testing approach utilizes Jest’s describe/it structure with multiple expect assertions to validate the function’s behavior. The implementation employs a systematic testing pattern that progresses through sequential numbers and includes strategic power-of-two values up to 1024, ensuring thorough validation of the algorithm’s logic.

Technical Details

Testing infrastructure:
  • Framework: Jest
  • Test Type: Unit Test
  • Testing Pattern: Multiple assertions within single test case
  • Import Structure: Direct module import

Best Practices Demonstrated

The test suite exemplifies several testing best practices including comprehensive edge case coverage, logical test organization, and clear test descriptions. The implementation uses Jest’s expect().toBe() syntax consistently and maintains a clear progression of test cases from simple to complex values.

trekhleb/javascript-algorithms

src/algorithms/math/is-power-of-two/__test__/isPowerOfTwo.test.js

            
import isPowerOfTwo from '../isPowerOfTwo';

describe('isPowerOfTwo', () => {
  it('should check if the number is made by multiplying twos', () => {
    expect(isPowerOfTwo(-1)).toBe(false);
    expect(isPowerOfTwo(0)).toBe(false);
    expect(isPowerOfTwo(1)).toBe(true);
    expect(isPowerOfTwo(2)).toBe(true);
    expect(isPowerOfTwo(3)).toBe(false);
    expect(isPowerOfTwo(4)).toBe(true);
    expect(isPowerOfTwo(5)).toBe(false);
    expect(isPowerOfTwo(6)).toBe(false);
    expect(isPowerOfTwo(7)).toBe(false);
    expect(isPowerOfTwo(8)).toBe(true);
    expect(isPowerOfTwo(10)).toBe(false);
    expect(isPowerOfTwo(12)).toBe(false);
    expect(isPowerOfTwo(16)).toBe(true);
    expect(isPowerOfTwo(31)).toBe(false);
    expect(isPowerOfTwo(64)).toBe(true);
    expect(isPowerOfTwo(1024)).toBe(true);
    expect(isPowerOfTwo(1023)).toBe(false);
  });
});