{"id":"0068fc7a6fd925de","repo":"jestjs/jest","slug":"could-not-find-an-object-to-spy-upon-for-methodn","errorCode":null,"errorMessage":"could not find an object to spy upon for ${methodName}()","messagePattern":"could not find an object to spy upon for (.+?)\\(\\)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/jest-jasmine2/src/jasmine/spyRegistry.ts","lineNumber":88,"sourceCode":"    accessType: keyof PropertyDescriptor,\n  ) => Spy;\n\n  constructor({\n    currentSpies = () => [],\n  }: {\n    currentSpies?: () => Array<Spy>;\n  } = {}) {\n    this.allowRespy = function (allow) {\n      this.respy = allow;\n    };\n\n    this.spyOn = (obj, methodName, accessType) => {\n      if (accessType) {\n        return this._spyOnProperty(obj, methodName, accessType);\n      }\n\n      if (obj === void 0) {\n        throw new Error(\n          getErrorMsg(\n            `could not find an object to spy upon for ${methodName}()`,\n          ),\n        );\n      }\n\n      if (methodName === void 0) {\n        throw new Error(getErrorMsg('No method name supplied'));\n      }\n\n      if (obj[methodName] === void 0) {\n        throw new Error(getErrorMsg(`${methodName}() method does not exist`));\n      }\n\n      if (obj[methodName] && isSpy(obj[methodName])) {\n        if (this.respy) {\n          return obj[methodName];\n        } else {","sourceCodeStart":70,"sourceCodeEnd":106,"githubUrl":"https://github.com/jestjs/jest/blob/f49721c78e195558b40913977c9230f5b7f559d8/packages/jest-jasmine2/src/jasmine/spyRegistry.ts#L70-L106","documentation":"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.","triggerScenarios":"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.","commonSituations":"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`.","solutions":["Confirm the target object is defined at the point `spyOn` runs — log it or add a precondition.","If spying on a module export, ensure the import resolved (check the module path and named export spelling).","If the value is set later, move the `spyOn` call into the test body or a `beforeEach` that runs after initialization."],"exampleFix":"// before\nspyOn(userRepo, 'find') // userRepo is undefined here\n// after\nconst userRepo = require('../userRepo');\nspyOn(userRepo, 'find')","handlingStrategy":"type-guard","validationCode":"if (obj == null) { throw new Error(`cannot spyOn on ${obj}`); }\nspyOn(obj, 'method');","typeGuard":"const isSpyTarget = (o: unknown): o is Record<string, any> =>\n  o != null && typeof o === 'object' || typeof o === 'function';","tryCatchPattern":"try { spyOn(maybeObj, 'm'); } catch (e) { if (!/<spyOn>/.test(String(e))) throw e; /* init obj, retry */ }","preventionTips":["Spy after the object is initialized — inside the test or a beforeEach that runs last.","Validate module imports resolve before spying on their exports."],"tags":["jasmine2","spy","spy-on","undefined"],"analyzedSha":"f49721c78e195558b40913977c9230f5b7f559d8","analyzedAt":"2026-08-03T20:16:28.571Z","schemaVersion":2}