vitest-dev/vitest · error · Error
Expected is not a Number
Error message
Expected is not a Number
What it means
Thrown by the CloseTo asymmetric matcher constructor when the sample is not a number (isA('Number') fails). closeTo asserts the received number is within a tolerance of the sample, so the expected value must be numeric.
Source
Thrown at packages/expect/src/jest-asymmetric-matchers.ts:346
return this.inverse ? !result : result
}
toString() {
return `String${this.inverse ? 'Not' : ''}Matching`
}
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: number) {
if (!isA('Number', other)) {
return false
}
let result = false
if (View on GitHub (pinned to d568f8ce37)
Solutions
- Pass a numeric sample: expect.closeTo(3.14159, 4).
- Coerce with Number() only if you are certain it is numeric.
- Use a different matcher for non-numeric closeness.
Example fix
// before
expect(result).toEqual(expect.closeTo('3.14', 2))
// after
expect(result).toEqual(expect.closeTo(3.14, 2)) Defensive patterns
Strategy: type-guard
Validate before calling
function asNumber(v: unknown): number {
if (typeof v !== 'number' || Number.isNaN(v)) {
throw new TypeError(`closeTo needs a number, got ${typeof v}`)
}
return v
}
expect(result).toEqual(expect.closeTo(asNumber(sample), precision)) Type guard
function isFiniteNumber(v: unknown): v is number {
return typeof v === 'number' && !Number.isNaN(v)
} Prevention
- Type the sample argument of closeTo as number.
- Reject stringified numbers explicitly rather than relying on coercion.
- Guard NaN inputs separately since isA('Number') still returns true for NaN.
When it happens
Trigger: Constructing expect.closeTo(value) (or .not.closeTo) where value is a string, object, null, etc. The first guard in the constructor throws.
Common situations: Passing a string that looks numeric ('3.14'); passing undefined; a variable typed loosely that holds a non-number after a refactor.
Related errors
- Expected is not a string
- You must provide an object to ${this.toString()}, not '${typ
- You must provide an array to ${this.toString()}, not '${type
- any() expects to be passed a constructor function. Please pa
- Expected is not a String or a RegExp
AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03).
Data as JSON: /data/errors/f944ce2f2e759671.json.
Report an issue: GitHub.