|
| 1 | +import * as firebase from 'firebase/app'; |
| 2 | +import { FirebaseApp, FirebaseAppConfig, AngularFireModule } from 'angularfire2'; |
| 3 | +import { AngularFireDatabase, AngularFireDatabaseModule, stateChanges, ChildEvent } from 'angularfire2/database'; |
| 4 | +import { TestBed, inject } from '@angular/core/testing'; |
| 5 | +import { COMMON_CONFIG } from '../test-config'; |
| 6 | +import 'rxjs/add/operator/skip'; |
| 7 | + |
| 8 | +// generate random string to test fidelity of naming |
| 9 | +const rando = () => (Math.random() + 1).toString(36).substring(7); |
| 10 | +const FIREBASE_APP_NAME = rando(); |
| 11 | + |
| 12 | +describe('stateChanges', () => { |
| 13 | + let app: FirebaseApp; |
| 14 | + let db: AngularFireDatabase; |
| 15 | + let createRef: (path: string) => firebase.database.Reference; |
| 16 | + let batch = {}; |
| 17 | + const items = [{ name: 'zero' }, { name: 'one' }, { name: 'two' }].map((item, i) => ( { key: i.toString(), ...item } )); |
| 18 | + Object.keys(items).forEach(function (key, i) { |
| 19 | + const itemValue = items[key]; |
| 20 | + batch[i] = itemValue; |
| 21 | + }); |
| 22 | + // make batch immutable to preserve integrity |
| 23 | + batch = Object.freeze(batch); |
| 24 | + |
| 25 | + beforeEach(() => { |
| 26 | + TestBed.configureTestingModule({ |
| 27 | + imports: [ |
| 28 | + AngularFireModule.initializeApp(COMMON_CONFIG, FIREBASE_APP_NAME), |
| 29 | + AngularFireDatabaseModule |
| 30 | + ] |
| 31 | + }); |
| 32 | + inject([FirebaseApp, AngularFireDatabase], (app_: FirebaseApp, _db: AngularFireDatabase) => { |
| 33 | + app = app_; |
| 34 | + db = _db; |
| 35 | + app.database().goOffline(); |
| 36 | + createRef = (path: string) => { app.database().goOffline(); return app.database().ref(path); }; |
| 37 | + })(); |
| 38 | + }); |
| 39 | + |
| 40 | + afterEach(done => { |
| 41 | + app.delete().then(done, done.fail); |
| 42 | + }); |
| 43 | + |
| 44 | + function prepareStateChanges(opts: { events?: ChildEvent[], skip: number } = { skip: 0 }) { |
| 45 | + const { events, skip } = opts; |
| 46 | + const aref = createRef(rando()); |
| 47 | + aref.set(batch); |
| 48 | + const changes = stateChanges(aref, events); |
| 49 | + return { |
| 50 | + changes: changes.skip(skip), |
| 51 | + ref: aref |
| 52 | + }; |
| 53 | + } |
| 54 | + |
| 55 | + it('should listen to all events by default', (done) => { |
| 56 | + |
| 57 | + const { changes } = prepareStateChanges({ skip: 2 }); |
| 58 | + changes.subscribe(action => { |
| 59 | + expect(action.key).toEqual('2'); |
| 60 | + expect(action.payload!.val()).toEqual(items[items.length - 1]); |
| 61 | + done(); |
| 62 | + }); |
| 63 | + |
| 64 | + }); |
| 65 | + |
| 66 | +}); |
0 commit comments