jestjs/jest · error · Error

could not find an object to spy upon for ${methodName}()

Error message

could not find an object to spy upon for ${methodName}()

What it means

Thrown by `SpyRegistry.spyOn` in spyRegistry.ts:88 when the target object is `undefined` (`obj === void 0`). The check fires before the method-name and existence checks, so the message names the requested method. jasmine2 requires a concrete host object to install the spy on.

Source

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

    accessType: keyof PropertyDescriptor,
  ) => Spy;

  constructor({
    currentSpies = () => [],
  }: {
    currentSpies?: () => Array<Spy>;
  } = {}) {
    this.allowRespy = function (allow) {
      this.respy = allow;
    };

    this.spyOn = (obj, methodName, accessType) => {
      if (accessType) {
        return this._spyOnProperty(obj, methodName, accessType);
      }

      if (obj === void 0) {
        throw new Error(
          getErrorMsg(
            `could not find an object to spy upon for ${methodName}()`,
          ),
        );
      }

      if (methodName === void 0) {
        throw new Error(getErrorMsg('No method name supplied'));
      }

      if (obj[methodName] === void 0) {
        throw new Error(getErrorMsg(`${methodName}() method does not exist`));
      }

      if (obj[methodName] && isSpy(obj[methodName])) {
        if (this.respy) {
          return obj[methodName];
        } else {

View on GitHub (pinned to f49721c78e)

Solutions

  1. Confirm the target object is defined at the point `spyOn` runs — log it or add a precondition.
  2. If spying on a module export, ensure the import resolved (check the module path and named export spelling).
  3. If the value is set later, move the `spyOn` call into the test body or a `beforeEach` that runs after initialization.

Example fix

// before
spyOn(userRepo, 'find') // userRepo is undefined here
// after
const userRepo = require('../userRepo');
spyOn(userRepo, 'find')
Defensive patterns

Strategy: type-guard

Validate before calling

if (obj == null) { throw new Error(`cannot spyOn on ${obj}`); }
spyOn(obj, 'method');

Type guard

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

Try / catch

try { spyOn(maybeObj, 'm'); } catch (e) { if (!/<spyOn>/.test(String(e))) throw e; /* init obj, retry */ }

Prevention

When it happens

Trigger: Calling `spyOn(undefined, 'method')`, `spyOn(null, 'method')` (null is not void 0 so passes this guard but fails later), or `spyOn(SomeService.method)` with a missing second argument where the destructured import resolved to undefined.

Common situations: Mocking a CommonJS module whose export was renamed; importing a named binding that does not exist in ESM (strict but resolves to undefined at runtime under interop); accessing an object before it is initialized in `beforeEach`.

Related errors


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