jestjs/jest · error · Error

Expected is not a Number

Error message

Expected is not a Number

What it means

CloseTo (expect.closeTo) asserts a received number is within precision decimal places of the expected sample; the constructor validates the sample is a Number via isA('Number', ...) (covers primitive and boxed Number). Non-numbers throw immediately because the floating-point comparison is meaningless otherwise.

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 = false;
    if (
      other === Number.POSITIVE_INFINITY &&

View on GitHub (pinned to f49721c78e)

Solutions

  1. Pass a number: expect.closeTo(5, 2).
  2. Coerce validated input: expect.closeTo(Number(value), 2) after checking Number.isFinite.
  3. Confirm the property you read actually exists (avoid undefined).

Example fix

// before
expect(result).toEqual(expect.closeTo(config.threshold, 2)); // threshold is '0.5'

// after
expect(result).toEqual(expect.closeTo(Number(config.threshold), 2));
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof sample !== 'number' && !(sample instanceof Number)) {
  throw new TypeError('expect.closeTo needs a number for expected');
}
expect.closeTo(sample, precision);

Type guard

function isNumberLike(x: unknown): x is number | Number {
  return typeof x === 'number' || x instanceof Number;
}

Try / catch

// constructor throws synchronously — validate expected before calling

Prevention

When it happens

Trigger: Calling expect.closeTo('5', 2), expect.closeTo(undefined, 2), expect.closeTo(null, 2), or expect.closeTo({value:5}, 2).

Common situations: Passing a string from user input without coercing; passing undefined because the expected value came from a missing object property; mixing up argument order.

Related errors


AI-assisted analysis of jestjs/jest@f49721c78e (2026-08-03). Data as JSON: /data/errors/04cd26a2f3845ffc.json. Report an issue: GitHub.