From 3943cc2ddbba17b50b706a79d7406340b4641b53 Mon Sep 17 00:00:00 2001 From: "Terence D. Honles" Date: Tue, 2 Jun 2020 10:35:27 -0700 Subject: [PATCH] allow spy throwError to throw an Object When using the following code to simulate a node error: spyOn(process, 'kill').and.throwError({code: 'ESRCH'}) The object passed in will be converted to a string by the Error constructor and result in '[object Object]' which is not very useful. This PR changes the ``throwError`` spy strategy to only convert strings into an Error object, but any other objects which are passed in will be thrown as is. This means the spy strategy can never emulate throwing a bare string ``throw 'error'``, but this would be a backward incompatible change. --- spec/core/SpyStrategySpec.js | 14 +++++++++++++- src/core/SpyStrategy.js | 4 ++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/spec/core/SpyStrategySpec.js b/spec/core/SpyStrategySpec.js index 5e454b64..76a3a1e2 100644 --- a/spec/core/SpyStrategySpec.js +++ b/spec/core/SpyStrategySpec.js @@ -70,7 +70,7 @@ describe('SpyStrategy', function() { expect(originalFn).not.toHaveBeenCalled(); }); - it('allows a non-Error to be thrown, wrapping it into an exception when executed', function() { + it('allows a string to be thrown, wrapping it into an exception when executed', function() { var originalFn = jasmine.createSpy('original'), spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); @@ -82,6 +82,18 @@ describe('SpyStrategy', function() { expect(originalFn).not.toHaveBeenCalled(); }); + it('allows a non-Error to be thrown when executed', function() { + var originalFn = jasmine.createSpy('original'), + spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); + + spyStrategy.throwError({ code: 'ESRCH' }); + + expect(function() { + spyStrategy.exec(); + }).toThrow({ code: 'ESRCH' }); + expect(originalFn).not.toHaveBeenCalled(); + }); + it('allows a fake function to be called instead', function() { var originalFn = jasmine.createSpy('original'), fakeFn = jasmine.createSpy('fake').and.returnValue(67), diff --git a/src/core/SpyStrategy.js b/src/core/SpyStrategy.js index 7e86abd6..41aa9258 100644 --- a/src/core/SpyStrategy.js +++ b/src/core/SpyStrategy.js @@ -150,10 +150,10 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @name SpyStrategy#throwError * @since 2.0.0 * @function - * @param {Error|String} something Thing to throw + * @param {Error|Object|String} something Thing to throw */ SpyStrategy.prototype.throwError = function(something) { - var error = something instanceof Error ? something : new Error(something); + var error = j$.isString_(something) ? new Error(something) : something; this.plan = function() { throw error; };