118 lines
2.7 KiB
JavaScript
118 lines
2.7 KiB
JavaScript
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).', () => {
|
|
const la = LiveArray(fakePouch, selector, opts);
|
|
|
|
expect(typeof la).toEqual('function');
|
|
expect(typeof la.subscribe).toEqual('function');
|
|
|
|
expect(JSON.stringify(la())).toEqual('[]');
|
|
});
|
|
|
|
it('has a "ready" subscribable that is fired once and subscribers cleared when the main subscribable has data for the first time.', () => {
|
|
let sub = null;
|
|
|
|
const db = {
|
|
changes: options => {
|
|
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 => {
|
|
return Promise.resolve({ docs: [{ _id: 234 }] });
|
|
}
|
|
};
|
|
|
|
const la = LiveArray(db, selector, opts);
|
|
|
|
return new Promise((resolve, reject) => {
|
|
const unsub = la.ready.subscribe(() => {
|
|
unsub();
|
|
resolve();
|
|
});
|
|
});
|
|
});
|
|
|
|
it('fires when data changes.', () => {
|
|
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 = LiveArray(db, selector, opts);
|
|
state = 1;
|
|
|
|
let innerState = 0;
|
|
|
|
return new Promise((resolve, reject) => {
|
|
const unsub = la.ready.subscribe(() => {
|
|
la.subscribe(data => {
|
|
if (data.length) {
|
|
expect(data[0]._id).toEqual(parseInt(changeKeys[innerState]));
|
|
}
|
|
innerState += 1;
|
|
|
|
resolve();
|
|
});
|
|
|
|
changeKeys.forEach(id => {
|
|
const doc = changes[parseInt(id)];
|
|
sub(doc);
|
|
});
|
|
|
|
unsub();
|
|
});
|
|
});
|
|
});
|
|
});
|