jestjs/jest · error · Error

<spyOn> : could not find an object to spy upon for ${propert

Error message

<spyOn> : could not find an object to spy upon for ${propertyName}
Usage: spyOn(<object>, <methodName>)

What it means

Thrown by SpyRegistry._spyOnProperty when the target object is falsy (spyRegistry.ts:154-159). This is the property-access variant of spyOn (invoked when an accessType like 'get'/'set' is supplied); it needs a real object whose property descriptor will be redefined.

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 8e6d128e4a)

Solutions

  1. Confirm the object is defined before spying: expect(obj).toBeDefined(); spyOn(obj, 'prop', 'get').
  2. Fix the import so the object resolves; for ESM use `import * as ns` and spy on ns.prop.
  3. Guard: if (obj) spyOn(obj, 'prop', 'get');.
  4. Run the test in isolation to rule out load-order issues.

Example fix

// before
spyOn(undefined, 'value', 'get');
// after
import * as cfg from './config';
spyOn(cfg, 'value', 'get');
Defensive patterns

Strategy: validation

Validate before calling

if (!obj) {
  throw new Error('spyOn property: target object is null/undefined; verify the import');
}
spyOn(obj, 'prop', 'get');

Type guard

const isObject = (v: unknown): v is Record<string, any> =>
  v !== null && v !== undefined && typeof v === 'object';

Prevention

When it happens

Trigger: spyOn(undefined, 'prop', 'get'), spyOn(null, 'prop', 'set'), or spyOn(obj, 'prop', 'get') where obj was destructured to undefined via a bad import.

Common situations: Switching from spyOn to the accessor form without re-checking the import; mocking a module whose default export is undefined under ESM; spying on a property of a lazily-initialised singleton that has not yet been constructed.

Related errors


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