Back to Repositories

Testing Trial Division Primality Algorithm in javascript-algorithms

This test suite validates the Trial Division primality testing algorithm implementation in JavaScript. It provides comprehensive test coverage for determining whether numbers are prime, handling both valid prime numbers and various edge cases including negative numbers, zero, and floating-point values.

Test Coverage Overview

The test suite provides extensive coverage of the trial division primality testing algorithm.

Key areas tested include:
  • Verification of known prime numbers (2, 3, 5, 11, 191, 199)
  • Validation of non-prime numbers (4, 6, 12, 14, 25)
  • Edge cases including negative numbers, zero, and floating-point values
  • Boundary testing with larger numbers (192, 200, 400)

Implementation Analysis

The testing approach utilizes Jest’s describe/it block structure with a helper function pattern for systematic test case execution.

Notable implementation features:
  • Centralized test function (primalityTest) for consistent verification
  • Parametrized testing approach for multiple input scenarios
  • Boolean return value validation for prime/non-prime determination

Technical Details

Testing infrastructure includes:
  • Jest testing framework
  • Function-based test organization
  • Expect assertions for boolean validation
  • Import-based module testing structure
  • Single responsibility test cases

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Comprehensive edge case coverage
  • Reusable test function implementation
  • Clear test case organization
  • Efficient test case grouping
  • Descriptive test naming conventions

trekhleb/javascript-algorithms

src/algorithms/math/primality-test/__test__/trialDivision.test.js

            
import trialDivision from '../trialDivision';

/**
 * @param {function(n: number)} testFunction
 */
function primalityTest(testFunction) {
  expect(testFunction(1)).toBe(false);
  expect(testFunction(2)).toBe(true);
  expect(testFunction(3)).toBe(true);
  expect(testFunction(5)).toBe(true);
  expect(testFunction(11)).toBe(true);
  expect(testFunction(191)).toBe(true);
  expect(testFunction(191)).toBe(true);
  expect(testFunction(199)).toBe(true);

  expect(testFunction(-1)).toBe(false);
  expect(testFunction(0)).toBe(false);
  expect(testFunction(4)).toBe(false);
  expect(testFunction(6)).toBe(false);
  expect(testFunction(12)).toBe(false);
  expect(testFunction(14)).toBe(false);
  expect(testFunction(25)).toBe(false);
  expect(testFunction(192)).toBe(false);
  expect(testFunction(200)).toBe(false);
  expect(testFunction(400)).toBe(false);

  // It should also deal with floats.
  expect(testFunction(0.5)).toBe(false);
  expect(testFunction(1.3)).toBe(false);
  expect(testFunction(10.5)).toBe(false);
}

describe('trialDivision', () => {
  it('should detect prime numbers', () => {
    primalityTest(trialDivision);
  });
});