import debug from 'debug'; import { tap } from 'rxjs/operators'; import { PubSub } from './pub-sub'; debug.enable('app:pubsub:*'); describe('PubSub', () => { let instance: PubSub; beforeEach(async () => { instance = new PubSub({ name: 'default', redis: { host: 'localhost', }, }); }); it('should be defined', () => { expect(instance).toBeDefined(); }); it('should can send and receive message', async () => { const arr = new Array(10) .fill(undefined) .map(() => Math.random().toString(36).slice(2, 8)); const results: string[] = []; instance .message$('test') .pipe( tap((val) => { console.log(val); }), ) .subscribe((val) => results.push(val)); await new Promise((r) => setTimeout(r, 1000)); await Promise.all([...arr.map((str) => instance.publish('test', str))]); await new Promise((r) => setTimeout(r, 1000)); expect(results).toMatchObject(arr); }); it('should complete', async () => { const arr = new Array(10) .fill(undefined) .map(() => Math.random().toString(36).slice(2, 8)); const results: string[] = []; instance .message$('test') .pipe( tap((val) => { console.log(val); }), ) .subscribe((val) => results.push(val)); await new Promise((r) => setTimeout(r, 1000)); await Promise.all([...arr.map((str) => instance.publish('test', str))]); await instance.finish('test'); await Promise.all([...arr.map((str) => instance.publish('test', str))]); await new Promise((r) => setTimeout(r, 1000)); expect(results).toMatchObject(arr); }); it('should error', async () => { const arr = new Array(10) .fill(undefined) .map(() => Math.random().toString(36).slice(2, 8)); const results: string[] = []; let error: string; instance .message$('test') .pipe( tap((val) => { console.log(val); }), ) .subscribe({ next: (val) => results.push(val), error: (err) => (error = err.message), }); await new Promise((r) => setTimeout(r, 1000)); await Promise.all([...arr.map((str) => instance.publish('test', str))]); await instance.throwError('test', 'TEST ERROR MESSAGE'); await Promise.all([...arr.map((str) => instance.publish('test', str))]); await new Promise((r) => setTimeout(r, 1000)); expect(results).toMatchObject(arr); expect(error).toEqual('TEST ERROR MESSAGE'); }); });