|
| 1 | +import { TestBed } from '@angular/core/testing'; |
| 2 | +import { type } from '@ngrx/signals'; |
| 3 | +import { Dispatcher, event, EventInstance, Events } from '../src'; |
| 4 | +import { SOURCE_TYPE } from '../src/events-service'; |
| 5 | + |
| 6 | +describe('Events', () => { |
| 7 | + it('is provided at the root level', () => { |
| 8 | + const events = TestBed.inject(Events); |
| 9 | + expect(events).toBeDefined(); |
| 10 | + }); |
| 11 | + |
| 12 | + describe('on', () => { |
| 13 | + const foo = event('foo'); |
| 14 | + const bar = event('bar', type<{ value: number }>()); |
| 15 | + const baz = event('baz'); |
| 16 | + |
| 17 | + it('emits events matching the provided event creators', () => { |
| 18 | + const events = TestBed.inject(Events); |
| 19 | + const dispatcher = TestBed.inject(Dispatcher); |
| 20 | + const emittedEvents: EventInstance<string, unknown>[] = []; |
| 21 | + |
| 22 | + events.on(foo, bar).subscribe((event) => emittedEvents.push(event)); |
| 23 | + |
| 24 | + dispatcher.dispatch(bar({ value: 10 })); |
| 25 | + dispatcher.dispatch(foo()); |
| 26 | + dispatcher.dispatch(baz()); |
| 27 | + dispatcher.dispatch(bar({ value: 100 })); |
| 28 | + |
| 29 | + expect(emittedEvents).toEqual([ |
| 30 | + { type: 'bar', payload: { value: 10 } }, |
| 31 | + { type: 'foo' }, |
| 32 | + { type: 'bar', payload: { value: 100 } }, |
| 33 | + ]); |
| 34 | + }); |
| 35 | + |
| 36 | + it('emits all events when called without arguments', () => { |
| 37 | + const events = TestBed.inject(Events); |
| 38 | + const dispatcher = TestBed.inject(Dispatcher); |
| 39 | + const emittedEvents: EventInstance<string, unknown>[] = []; |
| 40 | + |
| 41 | + events.on().subscribe((event) => emittedEvents.push(event)); |
| 42 | + |
| 43 | + dispatcher.dispatch(foo()); |
| 44 | + dispatcher.dispatch(bar({ value: 10 })); |
| 45 | + dispatcher.dispatch(baz()); |
| 46 | + dispatcher.dispatch(foo()); |
| 47 | + |
| 48 | + expect(emittedEvents).toEqual([ |
| 49 | + { type: 'foo' }, |
| 50 | + { type: 'bar', payload: { value: 10 } }, |
| 51 | + { type: 'baz' }, |
| 52 | + { type: 'foo' }, |
| 53 | + ]); |
| 54 | + }); |
| 55 | + |
| 56 | + it('adds SOURCE_TYPE to emitted events', () => { |
| 57 | + const events = TestBed.inject(Events); |
| 58 | + const dispatcher = TestBed.inject(Dispatcher); |
| 59 | + const sourceTypes: string[] = []; |
| 60 | + |
| 61 | + events |
| 62 | + .on() |
| 63 | + .subscribe((event) => sourceTypes.push((event as any)[SOURCE_TYPE])); |
| 64 | + |
| 65 | + dispatcher.dispatch(foo()); |
| 66 | + dispatcher.dispatch(bar({ value: 10 })); |
| 67 | + |
| 68 | + expect(sourceTypes).toEqual(['foo', 'bar']); |
| 69 | + }); |
| 70 | + }); |
| 71 | +}); |
0 commit comments