vitest-dev/vitest · error · Error
Expected is not a Number
Error message
Expected is not a Number
What it means
The CloseTo asymmetric matcher (expect.closeTo) requires its sample to be a Number; isA('Number', sample) rejects NaN and non-numbers. It is used for approximate floating-point equality within a precision.
Solutions
- Pass a real number: expect.closeTo(1.5, 2).
- Coerce validated numeric strings with Number(...) and confirm !Number.isNaN.
- For BigInt values, convert explicitly or use a different matcher.
Example fix
// before
expect(value).toEqual(expect.closeTo('1.50', 2))
// after
expect(value).toEqual(expect.closeTo(1.5, 2)) Defensive patterns
Strategy: type-guard
Validate before calling
function asCloseTo(sample, precision = 2) {
if (typeof sample !== 'number' || Number.isNaN(sample)) {
throw new TypeError('expect.closeTo needs a Number sample')
}
return expect.closeTo(sample, precision)
} Type guard
function isFiniteNumber(v): v is number {
return typeof v === 'number' && !Number.isNaN(v)
} Prevention
- Pass numeric literals to expect.closeTo.
- Coerce validated numeric strings with Number() first.
- Remember BigInt is not a Number — convert or pick another matcher.
When it happens
Trigger: expect.closeTo(sample) where sample is a string, null, object, or NaN.
Common situations: Passing a numeric string ('1.5') instead of a number; passing null from an optional field; passing a BigInt (not a Number).
Related errors
- any() expects to be passed a constructor function. Please…
- Expected is not a string
- Expected is not a String or a RegExp
- Precision is not a Number
- You must provide an array to
AI-assisted analysis of vitest-dev/vitest@1fa9837ec2 (2026-08-11).
Data as JSON: /api/errors/f944ce2f2e759671.
Report an issue: GitHub.
Appendix: 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 1fa9837ec2)