{"id":"9b69300ee8eac3ad","repo":"jestjs/jest","slug":"expected-value-must-be-a-number","errorCode":null,"errorMessage":"expected value must be a number","messagePattern":"expected value must be a number","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"packages/expect/src/matchers.ts","lineNumber":154,"sourceCode":"    // Passing the actual and expected objects so that a custom reporter\n    // could access them, for example in order to display a custom visual diff,\n    // or create a different error message\n    return {actual: received, expected, message, name: matcherName, pass};\n  },\n\n  toBeCloseTo(received: number, expected: number, precision = 2) {\n    const matcherName = 'toBeCloseTo';\n    const secondArgument = arguments.length === 3 ? 'precision' : undefined;\n    const isNot = this.isNot;\n    const options: MatcherHintOptions = {\n      isNot,\n      promise: this.promise,\n      secondArgument,\n      secondArgumentColor: (arg: string) => arg,\n    };\n\n    if (typeof expected !== 'number') {\n      throw new TypeError(\n        matcherErrorMessage(\n          matcherHint(matcherName, undefined, undefined, options),\n          `${EXPECTED_COLOR('expected')} value must be a number`,\n          printWithType('Expected', expected, printExpected),\n        ),\n      );\n    }\n\n    if (typeof received !== 'number') {\n      throw new TypeError(\n        matcherErrorMessage(\n          matcherHint(matcherName, undefined, undefined, options),\n          `${RECEIVED_COLOR('received')} value must be a number`,\n          printWithType('Received', received, printReceived),\n        ),\n      );\n    }\n","sourceCodeStart":136,"sourceCodeEnd":172,"githubUrl":"https://github.com/jestjs/jest/blob/f49721c78e195558b40913977c9230f5b7f559d8/packages/expect/src/matchers.ts#L136-L172","documentation":"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`.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Inspect the actual runtime value of the expected argument with a quick `console.log(typeof expectedVal, expectedVal)` before the assertion.","Coerce or normalize the value to a number before passing it: `Number(val)` or `parseFloat(val)`.","If the value is legitimately optional, guard the assertion: `if (typeof val === 'number') expect(x).toBeCloseTo(val);`.","Fix the data source so it yields a real number (parse JSON with a schema, fix the API response shape)."],"exampleFix":"// before\nexpect(total).toBeCloseTo(prices.subtotal); // prices.subtotal is undefined\n\n// after\nexpect(total).toBeCloseTo(Number(prices.subtotal));","handlingStrategy":"type-guard","validationCode":"if (typeof expectedVal !== 'number' || !Number.isFinite(expectedVal)) {\n  throw new Error(`expectedVal must be a finite number, got ${typeof expectedVal}`);\n}\nexpect(received).toBeCloseTo(expectedVal, precision);","typeGuard":"const isNumber = (v: unknown): v is number =>\n  typeof v === 'number' && Number.isFinite(v);","tryCatchPattern":"try {\n  expect(received).toBeCloseTo(expectedVal, precision);\n} catch (e) {\n  if (e instanceof TypeError && /must be a number/.test(e.message)) {\n    // handle type misuse separately from test failure\n  }\n  throw e;\n}","preventionTips":["Type the expected value as `number` in helper functions that build assertions.","Run TypeScript with strict type-checking so non-number values are flagged at compile time.","Add a lint rule or pre-assertion log when consuming numeric values from untyped sources (config, JSON)."],"tags":["jest","expect","type-validation","assertion","numeric","typescript"],"analyzedSha":"f49721c78e195558b40913977c9230f5b7f559d8","analyzedAt":"2026-08-03T20:16:28.571Z","schemaVersion":2}