From 317ba0c9254e447385414e2c57e1d81760f88aa6 Mon Sep 17 00:00:00 2001 From: Nicholas Jamieson Date: Tue, 16 Mar 2021 02:38:40 +1000 Subject: [PATCH] fix(fromEvent): throw if passed invalid target (#6136) Closes #5823 --- spec/observables/fromEvent-spec.ts | 13 ++++--------- src/internal/observable/fromEvent.ts | 14 ++++++-------- 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/spec/observables/fromEvent-spec.ts b/spec/observables/fromEvent-spec.ts index ee76bb72ca..8b8b4bdb20 100644 --- a/spec/observables/fromEvent-spec.ts +++ b/spec/observables/fromEvent-spec.ts @@ -181,20 +181,15 @@ describe('fromEvent', () => { expect(offHandler).to.equal(onHandler); }); - it('should error on invalid event targets', () => { + it('should throw if passed an invalid event target', () => { const obj = { addListener: () => { //noop } }; - - fromEvent(obj as any, 'click').subscribe({ - error(err: any) { - expect(err).to.exist - .and.be.instanceof(Error) - .and.have.property('message', 'Invalid event target'); - } - }); + expect(() => { + fromEvent(obj as any, 'click'); + }).to.throw(/Invalid event target/) }); it('should pass through options to addEventListener and removeEventListener', () => { diff --git a/src/internal/observable/fromEvent.ts b/src/internal/observable/fromEvent.ts index e23b6f1102..d17c775d1d 100644 --- a/src/internal/observable/fromEvent.ts +++ b/src/internal/observable/fromEvent.ts @@ -245,15 +245,13 @@ export function fromEvent( } } + // If add is falsy and we made it here, it's because we didn't + // match any valid target objects above. + if (!add) { + throw new TypeError('Invalid event target'); + } + return new Observable((subscriber) => { - // If add is falsy and we made it here, it's because we didn't - // match any valid target objects above. - if (!add) { - // TODO: We should probably discuss if throwing this at subscription-time - // is appropriate. It seems like it would be better (and easier to debug) - // to throw this when `fromEvent()` is called. - throw new TypeError('Invalid event target'); - } // The handler we are going to register. Forwards the event object, by itself, or // an array of arguments to the event handler, if there is more than one argument, // to the consumer.