From a81466d9e7f0b78ea6d1206c937e22e8e3407166 Mon Sep 17 00:00:00 2001 From: Stephan Bijzitter Date: Wed, 21 Oct 2015 12:44:52 +0200 Subject: [PATCH] Abort spying when the target cannot be spied on --- spec/core/SpyRegistrySpec.js | 26 ++++++++++++++++++++++++++ src/core/SpyRegistry.js | 5 +++++ 2 files changed, 31 insertions(+) diff --git a/spec/core/SpyRegistrySpec.js b/spec/core/SpyRegistrySpec.js index f7930172..52aef6a4 100644 --- a/spec/core/SpyRegistrySpec.js +++ b/spec/core/SpyRegistrySpec.js @@ -37,6 +37,32 @@ describe("SpyRegistry", function() { }).toThrowError(/has already been spied upon/); }); + it("checks if it can be spied upon", function() { + var scope = {}; + + function myFunc() { + return 1; + } + + Object.defineProperty(scope, 'myFunc', { + get: function() { + return myFunc; + } + }); + + var spies = [], + spyRegistry = new j$.SpyRegistry({currentSpies: function() { return spies; }}), + subject = { spiedFunc: scope.myFunc }; + + expect(function() { + spyRegistry.spyOn(scope, 'myFunc'); + }).toThrowError(/is not declared writable or has no setter/); + + expect(function() { + spyRegistry.spyOn(subject, 'spiedFunc'); + }).not.toThrowError(/is not declared writable or has no setter/); + }); + it("overrides the method on the object and returns the spy", function() { var originalFunctionWasCalled = false, spyRegistry = new j$.SpyRegistry(), diff --git a/src/core/SpyRegistry.js b/src/core/SpyRegistry.js index 43f9edfe..08f9c3ff 100644 --- a/src/core/SpyRegistry.js +++ b/src/core/SpyRegistry.js @@ -22,6 +22,11 @@ getJasmineRequireObj().SpyRegistry = function(j$) { throw new Error(methodName + ' has already been spied upon'); } + var descriptor = Object.getOwnPropertyDescriptor(obj, methodName); + if (!(descriptor.writable || descriptor.set)) { + throw new Error(methodName + ' is not declared writable or has no setter'); + } + var spy = j$.createSpy(methodName, obj[methodName]); currentSpies().push({