jestjs/jest · error · Error

Expected is not a Number

Error message

Expected is not a Number

What it means

closeTo / notCloseTo build a CloseTo matcher that compares a received number to an expected number within a precision tolerance. The constructor throws an Error if the `sample` (the expected value) is not a Number, because the floating-point comparison logic only makes sense for numbers.

Solutions

  1. Pass a numeric expected value: `expect.closeTo(1.5, 2)`.
  2. Parse/coerce the source: `Number(value)` and confirm it is finite before use.
  3. If the value may legitimately be non-numeric, branch the assertion rather than using closeTo.

Example fix

// before
expect(result).toEqual(expect.closeTo('1.50', 2)); // string, not Number

// after
expect(result).toEqual(expect.closeTo(1.5, 2));
Defensive patterns

Strategy: type-guard

Validate before calling

function closeToSafe(value, precision = 2) {
  if (typeof value !== 'number' || !Number.isFinite(value)) {
    throw new TypeError('closeTo requires a finite number');
  }
  return expect.closeTo(value, precision);
}

Type guard

function isFiniteNumber(v: unknown): v is number {
  return typeof v === 'number' && Number.isFinite(v);
}

const m = isFiniteNumber(value) ? expect.closeTo(value, precision) : expect.anything();

Prevention

When it happens

Trigger: Calling `expect.closeTo(value, precision?)` where value is not a number — e.g. a string, undefined, or null. Thrown at construction time, before any assertion.

Common situations: Passing a numeric string ('1.5') instead of a number; passing undefined from an optional config; forgetting to parse user input; expecting closeTo on a non-numeric field.

Related errors


AI-assisted analysis of jestjs/jest@8e6d128e4a (2026-08-10). Data as JSON: /api/errors/04cd26a2f3845ffc. Report an issue: GitHub.

Appendix: source

Thrown at packages/expect/src/asymmetricMatchers.ts:351

    return this.inverse ? !result : result;
  }

  toString() {
    return `String${this.inverse ? 'Not' : ''}Matching`;
  }

  override getExpectedType() {
    return 'string';
  }
}

class CloseTo extends AsymmetricMatcher<number> {
  private readonly precision: number;

  constructor(sample: number, precision = 2, inverse = false) {
    if (!isA('Number', sample)) {
      throw new Error('Expected is not a Number');
    }

    if (!isA('Number', precision)) {
      throw new Error('Precision is not a Number');
    }

    super(sample);
    this.inverse = inverse;
    this.precision = precision;
  }

  asymmetricMatch(other: unknown) {
    if (!isA<number>('Number', other)) {
      return false;
    }
    let result: boolean;
    if (
      other === Number.POSITIVE_INFINITY &&

View on GitHub (pinned to 8e6d128e4a)