|
| 1 | +import { Component } from '@angular/core'; |
| 2 | +import { TestBed } from '@angular/core/testing'; |
| 3 | +import { RxEffects } from '@rx-angular/state/effects'; |
| 4 | +import { of, tap } from 'rxjs'; |
| 5 | +import { rxEffects, RxEffectsSetupFn } from '../src/lib/effects'; |
| 6 | + |
| 7 | +describe(rxEffects, () => { |
| 8 | + it('should create RxEffects instance', () => { |
| 9 | + const { component } = setupComponent(); |
| 10 | + expect(component.effects).toBeInstanceOf(RxEffects); |
| 11 | + }); |
| 12 | + |
| 13 | + it('should register an observable', () => { |
| 14 | + const spy = jest.fn(); |
| 15 | + setupComponent(({ register }) => register(of('src').pipe(tap(spy)))); |
| 16 | + expect(spy).toHaveBeenCalledWith('src'); |
| 17 | + }); |
| 18 | + |
| 19 | + it('should register an observable and sideEffect fn', () => { |
| 20 | + const spy = jest.fn(); |
| 21 | + setupComponent(({ register }) => register(of('src'), spy)); |
| 22 | + expect(spy).toHaveBeenCalledWith('src'); |
| 23 | + }); |
| 24 | + |
| 25 | + it('should register multiple observables', () => { |
| 26 | + const spy = jest.fn(); |
| 27 | + setupComponent(({ register }) => { |
| 28 | + register(of('src').pipe(tap(spy))); |
| 29 | + register(of('src2'), spy); |
| 30 | + }); |
| 31 | + expect(spy.mock.calls[0][0]).toEqual('src'); |
| 32 | + expect(spy.mock.calls[1][0]).toEqual('src2'); |
| 33 | + }); |
| 34 | + |
| 35 | + it('should register a sideEffect fn on destroy', () => { |
| 36 | + const spy = jest.fn(); |
| 37 | + const { fixture } = setupComponent(({ registerOnDestroy }) => |
| 38 | + registerOnDestroy(spy) |
| 39 | + ); |
| 40 | + fixture.destroy(); |
| 41 | + expect(spy).toHaveBeenCalledWith(true); |
| 42 | + }); |
| 43 | + |
| 44 | + it('should call ngOnDestroy', () => { |
| 45 | + const { fixture, component } = setupComponent(); |
| 46 | + const spy = jest.spyOn(component.effects, 'ngOnDestroy'); |
| 47 | + expect(spy).not.toHaveBeenCalled(); |
| 48 | + fixture.destroy(); |
| 49 | + expect(spy).toHaveBeenCalled(); |
| 50 | + }); |
| 51 | +}); |
| 52 | + |
| 53 | +function setupComponent(setupFn?: RxEffectsSetupFn) { |
| 54 | + @Component({}) |
| 55 | + class TestComponent { |
| 56 | + readonly effects = rxEffects(setupFn); |
| 57 | + } |
| 58 | + |
| 59 | + TestBed.configureTestingModule({ |
| 60 | + declarations: [TestComponent], |
| 61 | + }); |
| 62 | + |
| 63 | + const fixture = TestBed.createComponent(TestComponent); |
| 64 | + |
| 65 | + return { |
| 66 | + fixture, |
| 67 | + component: fixture.componentInstance, |
| 68 | + }; |
| 69 | +} |
0 commit comments