如何监视嵌套方法,jasmine

时间:2018-03-05 09:01:39

标签: angular typescript firebase jasmine google-cloud-firestore

我需要测试一个函数,我需要帮助的唯一测试用例是检查是否已调用dataCollection.add()方法。我认为这里需要间谍,但任何建议都会受到高度赞赏。

以下是我需要测试的功能,其中包含dataCollection.add()方法:

...
constructor(private _firebase: AngularFirestore, private _read: ReadService) {}

createRootCollectionDocument$(collection: string, data: any): Observable<firebase.firestore.DocumentReference> {
   const testt = this._firebase.collection(collection);
   const dataCollection: AngularFirestoreCollection<any> = this._firebase.collection(collection);
    return Observable.from(
       dataCollection.add({ ...data }).catch((err: firebase.firestore.FirestoreError) => {
          throw err.message;
        })
     );
 }

这是我的测试用例

...
beforeEach(() => {
   service = TestBed.get(CrudService);
}

it('uses the firebase collection.add method', () => {
      return service.createRootCollectionDocument$(collectionStub, dataStub).toPromise().then((result) => {
         ...
      })
 });           
...

提前致谢!

1 个答案:

答案 0 :(得分:2)

您可以存根this._firebase.collection以返回模拟对象,然后看到其add函数被调用。

it('uses the firebase collection.add method', () => {

      let mockAdder = jasmine.createSpyObj("adder", ["add"]);
      jasmine.spyOn(service["_firebase"], "collection").andReturn(mockAdder);

      return service.createRootCollectionDocument$(collectionStub, dataStub).toPromise().then((result) => {

          expect(mockAdder.add).toHaveBeenCalled();

      });
});