diff --git a/spec/core/GlobalErrorsSpec.js b/spec/core/GlobalErrorsSpec.js index 3880b041..42f9f37c 100644 --- a/spec/core/GlobalErrorsSpec.js +++ b/spec/core/GlobalErrorsSpec.js @@ -193,4 +193,34 @@ describe('GlobalErrors', function() { 'foo' ); }); + + it('reports unhandledRejection in browser', function() { + var fakeGlobal = { + addEventListener: jasmine.createSpy('addEventListener'), + removeEventListener: jasmine.createSpy('removeEventListener'), + onerror: jasmine.createSpy('onerror') + }, + handler = jasmine.createSpy('errorHandler'), + errors = new jasmineUnderTest.GlobalErrors(fakeGlobal); + + errors.install(); + expect(fakeGlobal.addEventListener).toHaveBeenCalledWith( + 'unhandledrejection', + jasmine.any(Function) + ); + + errors.pushListener(handler); + + var addedListener = fakeGlobal.addEventListener.calls.argsFor(0)[1]; + addedListener({ reason: new Error('bar') }); + + expect(handler).toHaveBeenCalledWith('Unhandled Rejection: Error: bar'); + + errors.uninstall(); + + expect(fakeGlobal.removeEventListener).toHaveBeenCalledWith( + 'unhandledrejection', + addedListener + ); + }); }); diff --git a/src/core/GlobalErrors.js b/src/core/GlobalErrors.js index 2c58e684..2fe4725d 100644 --- a/src/core/GlobalErrors.js +++ b/src/core/GlobalErrors.js @@ -63,8 +63,25 @@ getJasmineRequireObj().GlobalErrors = function(j$) { var originalHandler = global.onerror; global.onerror = onerror; + var browserRejectionHandler = function browserRejectionHandler(event) { + onerror('Unhandled Rejection: ' + event.reason); + }; + + if (global.addEventListener) { + global.addEventListener( + 'unhandledrejection', + browserRejectionHandler + ); + } + this.uninstall = function uninstall() { global.onerror = originalHandler; + if (global.removeEventListener) { + global.removeEventListener( + 'unhandledrejection', + browserRejectionHandler + ); + } }; } };