|
| 1 | +import { from, toArray } from 'rxjs'; |
| 2 | +import { tapOnce, tapOnceOnFirstTruthy } from './tap-once'; |
| 3 | + |
| 4 | +describe(tapOnce.name, () => { |
| 5 | + it('should execute the function only once at the specified index', (done) => { |
| 6 | + const tapFn = jest.fn(); |
| 7 | + const in$ = from([1, 2, 3, 4, 5]); |
| 8 | + const out$ = in$.pipe(tapOnce(tapFn, 2)); |
| 9 | + |
| 10 | + out$.pipe(toArray()).subscribe((r) => { |
| 11 | + expect(r).toEqual([1, 2, 3, 4, 5]); |
| 12 | + expect(tapFn).toHaveBeenCalledTimes(1); |
| 13 | + expect(tapFn).toHaveBeenCalledWith(3); |
| 14 | + done(); |
| 15 | + }); |
| 16 | + }); |
| 17 | + |
| 18 | + it('should execute the function only once at the default index 0', (done) => { |
| 19 | + const tapFn = jest.fn(); |
| 20 | + const in$ = from([1, 2, 3, 4, 5]); |
| 21 | + const out$ = in$.pipe(tapOnce(tapFn)); |
| 22 | + |
| 23 | + out$.pipe(toArray()).subscribe((r) => { |
| 24 | + expect(r).toEqual([1, 2, 3, 4, 5]); |
| 25 | + expect(tapFn).toHaveBeenCalledTimes(1); |
| 26 | + expect(tapFn).toHaveBeenCalledWith(1); |
| 27 | + done(); |
| 28 | + }); |
| 29 | + }); |
| 30 | + |
| 31 | + it('should throw an error if tapIndex is negative', () => { |
| 32 | + expect(() => tapOnce(() => {}, -1)).toThrow( |
| 33 | + 'tapIndex must be a non-negative integer', |
| 34 | + ); |
| 35 | + }); |
| 36 | +}); |
| 37 | + |
| 38 | +describe(tapOnceOnFirstTruthy.name, () => { |
| 39 | + it('should execute the function only once on the first truthy value', (done) => { |
| 40 | + const tapFn = jest.fn(); |
| 41 | + const in$ = from([0, null, false, 3, 4, 5]); |
| 42 | + const out$ = in$.pipe(tapOnceOnFirstTruthy(tapFn)); |
| 43 | + |
| 44 | + out$.pipe(toArray()).subscribe((r) => { |
| 45 | + expect(r).toEqual([0, null, false, 3, 4, 5]); |
| 46 | + expect(tapFn).toHaveBeenCalledTimes(1); |
| 47 | + expect(tapFn).toHaveBeenCalledWith(3); |
| 48 | + done(); |
| 49 | + }); |
| 50 | + }); |
| 51 | + |
| 52 | + it('should not execute the function if there are no truthy values', (done) => { |
| 53 | + const tapFn = jest.fn(); |
| 54 | + const in$ = from([0, null, false, undefined]); |
| 55 | + const out$ = in$.pipe(tapOnceOnFirstTruthy(tapFn)); |
| 56 | + |
| 57 | + out$.pipe(toArray()).subscribe((r) => { |
| 58 | + expect(r).toEqual([0, null, false, undefined]); |
| 59 | + expect(tapFn).not.toHaveBeenCalled(); |
| 60 | + done(); |
| 61 | + }); |
| 62 | + }); |
| 63 | + |
| 64 | + it('should execute the function only once even if there are multiple truthy values', (done) => { |
| 65 | + const tapFn = jest.fn(); |
| 66 | + const in$ = from([1, 2, 3, 4, 5]); |
| 67 | + const out$ = in$.pipe(tapOnceOnFirstTruthy(tapFn)); |
| 68 | + |
| 69 | + out$.pipe(toArray()).subscribe((r) => { |
| 70 | + expect(r).toEqual([1, 2, 3, 4, 5]); |
| 71 | + expect(tapFn).toHaveBeenCalledTimes(1); |
| 72 | + expect(tapFn).toHaveBeenCalledWith(1); |
| 73 | + done(); |
| 74 | + }); |
| 75 | + }); |
| 76 | +}); |
0 commit comments