import { LiveArray } from '../src/livearray.js'; import { pouchDocArrayHash } from '../src/utils.js'; describe('A LiveArray', () => { let fakePouch; const selector = {}; const opts = {}; beforeEach(() => { fakePouch = { find: () => {}, changes: () => fakePouch, on: () => fakePouch }; }); it('returns a computed (subscribable).', async () => { const la = await LiveArray(fakePouch, selector, opts); expect(typeof la).toEqual('function'); expect(typeof la.subscribe).toEqual('function'); expect(JSON.stringify(la())).toEqual('[]'); }); it('fires when data changes.', async () => { let state = 0; const changes = { 234: { id: 234, deleted: false, doc: { _id: 234 } }, 34: { id: 34, deleted: true, doc: { _id: 34 } }, 4564565: { id: 4564565, deleted: false, doc: { _id: 4564565 } } }; const changeKeys = Object.keys(changes); let sub = null; const db = { changes: options => { expect(state).toEqual(1); expect(options.live).toEqual(true); expect(options.since).toEqual('now'); expect(options.selector).toBe(selector); return db; }, on: (eventName, callback) => { if (eventName == 'change') { sub = callback; } expect(['change', 'error'].indexOf(eventName) !== -1).toBeTruthy(); return db; }, cancel: () => (sub = null), find: async selector => { const doc = changes[parseInt(changeKeys[state - 1])]; state += 1; if (doc === undefined || doc.deleted) { return Promise.resolve({ docs: [] }); } return Promise.resolve({ docs: [doc.doc] }); } }; const la = await LiveArray(db, selector, opts); state = 1; let innerState = 0; la.subscribe(data => { if (data.length) { expect(data[0]._id).toEqual(parseInt(changeKeys[innerState])); } innerState += 1; }); changeKeys.forEach(id => { const doc = changes[parseInt(id)]; sub(doc); }); }); });