jestjs/jest · error · TypeError

expected value must be a number

Error message

expected value must be a number

What it means

Thrown by the `toBeCloseTo` matcher (matchers.ts:142) when its first argument (the `expected` value to compare against) is not a number. `toBeCloseTo` performs floating-point comparison within a precision threshold, so the reference value must be numeric to compute the absolute difference `Math.abs(expected - received)`. Jest throws this synchronously as a `TypeError` before any comparison logic runs, because the arithmetic would otherwise produce `NaN`.

Source

Thrown at packages/expect/src/matchers.ts:154

    // Passing the actual and expected objects so that a custom reporter
    // could access them, for example in order to display a custom visual diff,
    // or create a different error message
    return {actual: received, expected, message, name: matcherName, pass};
  },

  toBeCloseTo(received: number, expected: number, precision = 2) {
    const matcherName = 'toBeCloseTo';
    const secondArgument = arguments.length === 3 ? 'precision' : undefined;
    const isNot = this.isNot;
    const options: MatcherHintOptions = {
      isNot,
      promise: this.promise,
      secondArgument,
      secondArgumentColor: (arg: string) => arg,
    };

    if (typeof expected !== 'number') {
      throw new TypeError(
        matcherErrorMessage(
          matcherHint(matcherName, undefined, undefined, options),
          `${EXPECTED_COLOR('expected')} value must be a number`,
          printWithType('Expected', expected, printExpected),
        ),
      );
    }

    if (typeof received !== 'number') {
      throw new TypeError(
        matcherErrorMessage(
          matcherHint(matcherName, undefined, undefined, options),
          `${RECEIVED_COLOR('received')} value must be a number`,
          printWithType('Received', received, printReceived),
        ),
      );
    }

View on GitHub (pinned to f49721c78e)

Solutions

  1. Inspect the actual runtime value of the expected argument with a quick `console.log(typeof expectedVal, expectedVal)` before the assertion.
  2. Coerce or normalize the value to a number before passing it: `Number(val)` or `parseFloat(val)`.
  3. If the value is legitimately optional, guard the assertion: `if (typeof val === 'number') expect(x).toBeCloseTo(val);`.
  4. Fix the data source so it yields a real number (parse JSON with a schema, fix the API response shape).

Example fix

// before
expect(total).toBeCloseTo(prices.subtotal); // prices.subtotal is undefined

// after
expect(total).toBeCloseTo(Number(prices.subtotal));
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof expectedVal !== 'number' || !Number.isFinite(expectedVal)) {
  throw new Error(`expectedVal must be a finite number, got ${typeof expectedVal}`);
}
expect(received).toBeCloseTo(expectedVal, precision);

Type guard

const isNumber = (v: unknown): v is number =>
  typeof v === 'number' && Number.isFinite(v);

Try / catch

try {
  expect(received).toBeCloseTo(expectedVal, precision);
} catch (e) {
  if (e instanceof TypeError && /must be a number/.test(e.message)) {
    // handle type misuse separately from test failure
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling `expect(x).toBeCloseTo(y)` where `y` is a string, undefined, null, object, or NaN (e.g. `expect(1.5).toBeCloseTo('1.5')`, `expect(price).toBeCloseTo(undefined)`, or destructuring a property that does not exist like `expect(n).toBeCloseTo(config.precision)` where `config.precision` is undefined). Also triggered by passing the precision argument in the wrong position: `expect(1.0).toBeCloseTo(2)` is fine, but `expect(1.0).toBeCloseTo('2', 2)` fails here.

Common situations: Reading expected values from a config file or JSON where numbers arrive as strings; passing a BigInt where a number was expected; an API or helper that returns `undefined` for missing fields that the test assumed was numeric; porting tests from a loosely-typed assertion library.

Related errors


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