I have a angularfire2 function that I'd like to test. The issue I'm running into is I have no idea how to mock the anonymous function call made by this.db.collection()
let along how to mock the piped functions. I'd like to test what value was passed to the ref.orderBy function, and the results returned by the pipe. How would I got about doing this?
sortedList(collection, orderByProperty){
return this.db.collection(collection, ref => {
return ref.orderBy(orderByProperty, 'asc')
})
.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
}))
);
}
..
import { TestBed } from '@angular/core/testing';
import { of } from "rxjs";
import { FirebaseService } from './firebase.service';
import { AngularFirestore } from '@angular/fire/firestore';
describe('FirebaseService', () => {
let service: FirebaseService;
const mockedData = [{
payload:{
doc:{
id:"zyx",
data:()=>{
return {hello:"world"}
}
}
},
},{
payload:{
doc:{
id:"abc",
data:()=>{
return {hello:"goodbye"}
}
}
}
}]
var afSpy = jasmine.createSpyObj('AngularFirestore', ['collection', 'snapshotChanges', 'pipe']);
afSpy.collection.and.returnValue(afSpy);
afSpy.snapshotChanges.and.returnValue(afSpy);
afSpy.pipe.and.returnValue(of(mockedData))
beforeEach(() => {
TestBed.configureTestingModule({
providers:[
{ provide: AngularFirestore, useValue: afSpy }
],
})
service = TestBed.get(FirebaseService); //get the testbed and set it so we can use it in our functions
});
it('should return a sorted list', () => {
service.sortedList('fakeCollection', 'id').subscribe(res=>{
expect(res).toEqual([{hello:"world", id:"zyx"}, {hello:"goodbye", id:"abc"}])
})
expect(afSpy.pipe).toHaveBeenCalled();
});
});
......................................................................................