jestjs/jest · error · Error

Cannot replace the ` ` property because it has a getter…

Error message

Cannot replace the `${String(propertyKey)}` property because it has a getter. Use `jest.spyOn(object, '${String(propertyKey)}', 'get').mockReturnValue(value)` instead.

What it means

Thrown by jest.replaceProperty when the descriptor has a getter. Replacing a getter-backed value would silently discard the getter semantics, so Jest refuses and points you to spyOn with accessType 'get', which correctly wraps the getter.

Solutions

  1. Use jest.spyOn(obj,'x','get').mockReturnValue(value) to override the getter's return.
  2. If you need to fully swap the property, redefine it without a getter first (only if configurable).
  3. Prefer module-level jest.mock for source-owned code.

Example fix

// before
jest.replaceProperty(obj, 'version', '2.0'); // version has a getter
// after
jest.spyOn(obj, 'version', 'get').mockReturnValue('2.0');
Defensive patterns

Strategy: validation

Validate before calling

const d = Object.getOwnPropertyDescriptor(obj, propertyKey);
if (d?.get) {
  jest.spyOn(obj, propertyKey, 'get').mockReturnValue(value);
} else {
  jest.replaceProperty(obj, propertyKey, value);
}

Type guard

const hasGetter = (o: object, k: PropertyKey): boolean =>
  Object.getOwnPropertyDescriptor(o, k)?.get !== undefined;

Prevention

When it happens

Trigger: jest.replaceProperty(obj,'x',v) where x is declared with Object.defineProperty({get:...}) or a class accessor property.

Common situations: Class getter properties; config objects with computed getters; framework objects exposing derived values.

Related errors


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

Appendix: source

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

    while (!descriptor && proto !== null) {
      descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey);
      proto = Object.getPrototypeOf(proto);
    }
    if (!descriptor) {
      throw new Error(
        `Property \`${String(
          propertyKey,
        )}\` does not exist in the provided object`,
      );
    }
    if (!descriptor.configurable) {
      throw new Error(
        `Property \`${String(propertyKey)}\` is not declared configurable`,
      );
    }

    if (descriptor.get !== undefined) {
      throw new Error(
        `Cannot replace the \`${String(
          propertyKey,
        )}\` property because it has a getter. Use \`jest.spyOn(object, '${String(
          propertyKey,
        )}', 'get').mockReturnValue(value)\` instead.`,
      );
    }

    if (descriptor.set !== undefined) {
      throw new Error(
        `Cannot replace the \`${String(
          propertyKey,
        )}\` property because it has a setter. Use \`jest.spyOn(object, '${String(
          propertyKey,
        )}', 'set').mockReturnValue(value)\` instead.`,
      );
    }

View on GitHub (pinned to 8e6d128e4a)