jestjs/jest · error · Error

Cannot use replaceProperty on a primitive value;

Error message

Cannot use replaceProperty on a primitive value; ${this._typeOf(object)} given

What it means

Thrown by jest.replaceProperty when the first argument is null, undefined, or a primitive. Like spyOn, replaceProperty needs an object/function to attach the replacement descriptor to.

Solutions

  1. Log the first argument and confirm it is an object/function at runtime.
  2. Fix the import path / named-vs-default usage.
  3. Pass the object that owns the property rather than a primitive.

Example fix

// before
jest.replaceProperty(settings, 'timeout', 5000); // settings is undefined
// after
import * as settings from './settings';
jest.replaceProperty(settings, 'timeout', 5000);
Defensive patterns

Strategy: type-guard

Validate before calling

if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
  throw new TypeError(`replaceProperty target must be object/function, got ${typeof target}`);
}
jest.replaceProperty(target, key, value);

Type guard

const isReplaceable = (x: unknown): x is object =>
  x != null && (typeof x === 'object' || typeof x === 'function');

Prevention

When it happens

Trigger: jest.replaceProperty(null,'x',v); jest.replaceProperty(undefined,'x',v); jest.replaceProperty('str','length',99); jest.replaceProperty(3,'toString',fn).

Common situations: The target import resolved to undefined (wrong path, named/default mismatch, ESM/CJS interop); tree-shaking removed the binding; passing a primitive export instead of its holder object.

Related errors


AI-assisted analysis of jestjs/jest@8e6d128e4a (2026-08-10). Data as JSON: /api/errors/d0cecf21876c7907. Report an issue: GitHub.

Appendix: source

Thrown at packages/jest-mock/src/index.ts:1459

        // @ts-expect-error - wrong context
        return original.apply(this, arguments);
      });
    }

    Object.defineProperty(object, propertyKey, descriptor);
    return descriptor[accessType] as Mock;
  }

  replaceProperty<T extends object, K extends keyof T>(
    object: T,
    propertyKey: K,
    value: T[K],
  ): Replaced<T[K]> {
    if (
      object == null ||
      (typeof object !== 'object' && typeof object !== 'function')
    ) {
      throw new Error(
        `Cannot use replaceProperty on a primitive value; ${this._typeOf(
          object,
        )} given`,
      );
    }

    if (propertyKey == null) {
      throw new Error('No property name supplied');
    }

    let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey);
    let proto = Object.getPrototypeOf(object);
    while (!descriptor && proto !== null) {
      descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey);
      proto = Object.getPrototypeOf(proto);
    }
    if (!descriptor) {
      throw new Error(

View on GitHub (pinned to 8e6d128e4a)