jestjs/jest · error · Error

could not find an object to spy upon for ${propertyName}

Error message

could not find an object to spy upon for ${propertyName}

What it means

Thrown by `SpyRegistry._spyOnProperty` in spyRegistry.ts:155 when the target object is falsy (`!obj`). This is the property-access variant of `spyOn` (used by `spyOnProperty`), reached when an `accessType` argument is supplied. The registry needs a real host object.

Source

Thrown at packages/jest-jasmine2/src/jasmine/spyRegistry.ts:155

        restoreStrategy = function () {
          if (!delete obj[methodName]) {
            obj[methodName] = originalMethod;
          }
        };
      }

      currentSpies().push({
        restoreObjectToOriginalState: restoreStrategy,
      } as Spy);

      obj[methodName] = spiedMethod;

      return spiedMethod;
    };

    this._spyOnProperty = function (obj, propertyName, accessType = 'get') {
      if (!obj) {
        throw new Error(
          getErrorMsg(
            `could not find an object to spy upon for ${propertyName}`,
          ),
        );
      }

      if (!propertyName) {
        throw new Error(getErrorMsg('No property name supplied'));
      }

      let descriptor: PropertyDescriptor | undefined;
      try {
        descriptor = Object.getOwnPropertyDescriptor(obj, propertyName);
      } catch {
        // IE 8 doesn't support `definePropery` on non-DOM nodes
      }

      if (!descriptor) {

View on GitHub (pinned to f49721c78e)

Solutions

  1. Confirm the target object is defined where `spyOnProperty` runs.
  2. Move the spy into a `beforeEach`/test body that runs after the object is created.
  3. If mocking a module export, verify the import path and named export.

Example fix

// before
spyOnProperty(undefined, 'host', 'get')
// after
const svc = require('../svc');
spyOnProperty(svc, 'host', 'get')
Defensive patterns

Strategy: type-guard

Validate before calling

if (!obj) { throw new Error('spyOnProperty needs a target object'); }
spyOnProperty(obj, 'p', 'get');

Type guard

const isSpyTarget = (o: unknown): o is Record<string, any> =>
  o != null && (typeof o === 'object' || typeof o === 'function');

Prevention

When it happens

Trigger: Calling `spyOnProperty(undefined, 'x', 'get')`, `spyOnProperty(null, 'x', 'get')`, or `jest.spyOn(obj, 'x', 'get')` where `obj` resolved to undefined at runtime.

Common situations: Importing a named binding that does not exist under ESM/CJS interop; spying before the object is initialized; refactor leaving a stale reference.

Related errors


AI-assisted analysis of jestjs/jest@f49721c78e (2026-08-03). Data as JSON: /data/errors/2c9cc70848757eaa.json. Report an issue: GitHub.