Mocking Firestore collection in angular TestBed
Ok, I finally have managed mocking of Firestore collections. I give an example of different service:
SUT
import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Administrative } from '../model/administrative';
@Injectable()
export class AdministrativeService {
administratives: Administrative[] = [];
constructor(private db: AngularFirestore) {
this.db.collection<Administrative>('administrative').valueChanges()
.subscribe(data => this.administratives = data);
}
getPath(uname: string): string[] {
let current = this.administratives.find((a: Administrative) => a.uname === uname);
const result: string[] = [current.name];
while (current.parent) {
current = this.administratives.find((a: Administrative) => a.uname === current.parent);
result.unshift(current.name);
}
return result;
}
}
TEST
import { TestBed, inject } from '@angular/core/testing';
import { AdministrativeService } from './administrative.service';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Rx';
import { Administrative } from '../model/administrative';
const input: Administrative[][] = [[
{ name: 'Polska', uname: 'polska', parent: ''},
{ name: 'Dolnośląskie', uname: 'dolnoslaskie', parent: 'polska'},
{ name: 'Wrocław', uname: 'wroclaw', parent: 'dolnoslaskie'}
]];
const data = Observable.from(input);
const collectionStub = {
valueChanges: jasmine.createSpy('valueChanges').and.returnValue(data)
}
const angularFiresotreStub = {
collection: jasmine.createSpy('collection').and.returnValue(collectionStub)
}
describe('AdministrativeService', () => {
let service: AdministrativeService;
let angularFirestore: AngularFirestore;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AdministrativeService,
{ provide: AngularFirestore, useValue: angularFiresotreStub }
]
});
service = TestBed.get(AdministrativeService);
angularFirestore = TestBed.get(AngularFirestore);
});
it('should be created', () => {
expect(service).toBeTruthy();
expect(angularFiresotreStub.collection).toHaveBeenCalledWith('administrative');
});
it('gets hierarchy path', () => {
const result = service.getPath('wroclaw');
expect(result).toEqual(['Polska', 'Dolnośląskie', 'Wrocław']);
});
});