vitest-dev/vitest · error · Error

Precision is not a Number

Error message

Precision is not a Number

What it means

Thrown by the CloseTo asymmetric matcher constructor when the precision argument is not a number. Precision controls the tolerance (10 ** -precision / 2); a non-numeric precision makes the comparison undefined.

Source

Thrown at packages/expect/src/jest-asymmetric-matchers.ts:350

  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 (
      other === Number.POSITIVE_INFINITY
      && this.sample === Number.POSITIVE_INFINITY
    ) {
      result = true // Infinity - Infinity is NaN

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Pass a numeric precision or omit it to use the default of 2.
  2. Ensure the precision variable is typed as number.
  3. If you derived precision from user input, coerce and validate it first.

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 asPrecision(v: unknown): number {
  if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) {
    throw new TypeError(`closeTo precision must be a non-negative integer, got ${typeof v}`)
  }
  return v
}
expect(result).toEqual(expect.closeTo(sample, asPrecision(p)))

Type guard

function isNonNegativeInt(v: unknown): v is number {
  return typeof v === 'number' && Number.isInteger(v) && v >= 0
}

Prevention

When it happens

Trigger: Constructing expect.closeTo(sample, precision) where precision is a string, object, null, etc. The default is 2, but passing an explicit non-number triggers the second constructor guard.

Common situations: Passing precision as a string ('2'); passing an options object by mistake; refactor introducing a non-number precision variable.

Related errors


AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03). Data as JSON: /data/errors/e6248eef8af86515.json. Report an issue: GitHub.