Course contentsShow
← JavaScript
Lesson 2676 of 2,72354. Testing in JavaScriptFree lesson

Number Comparison Assertions

Using toBeGreaterThan, toBeLessThan, and closeness checks for floating-point numbers.

Number Comparison Assertions

You'll learn how to compare numbers in tests using relational assertions and handle floating-point precision issues.

When testing numeric calculations, you often need more than simple equality checks. You need to verify that a value is greater than, less than, or approximately equal to an expected number—especially when dealing with decimals that can't be represented precisely in binary.

Relational Assertions

Most test frameworks provide matchers for comparing numbers:

describe('Temperature converter', () => {
  it('converts freezing point correctly', () => {
    const celsius = 0;
    const fahrenheit = celsiusToFahrenheit(celsius);
    
    expect(fahrenheit).toBe(32);
    expect(fahrenheit).toBeGreaterThan(31);
    expect(fahrenheit).toBeLessThan(33);
  });

  it('validates temperature range', () => {
    const temp = getRandomTemperature();
    
    expect(temp).toBeGreaterThanOrEqual(0);
    expect(temp).toBeLessThanOrEqual(100);
  });
});

Floating-Point Precision

Computers can't always represent decimal numbers exactly. 0.1 + 0.2 equals 0.30000000000000004, not 0.3. For these cases, use closeness checks:

describe('Financial calculations', () => {
  it('calculates interest correctly', () => {
    const result = calculateInterest(1000, 0.03);
    
    // This might fail due to floating-point precision
    // expect(result).toBe(30);
    
    // Instead, check if it's close enough (within tolerance)
    expect(result).toBeCloseTo(30, 2); // Within 0.01
  });
});

The second argument to toBeCloseTo() specifies decimal precision—how many digits should match.

Key Takeaway: Use toBeGreaterThan and toBeLessThan for range validation, and toBeCloseTo for floating-point comparisons where tiny precision differences don't matter.