首页 > 解决方案 > 我如何在茉莉花中模拟 AngularFirestore 链式方法?

问题描述

我如何模拟 angularfirestore 并测试placeOrder方法?


constructor(private afs: AngularFirestore) {}

placeOrder(order: Order, restaurantId: string): Observable<void> {
   return from(this.afs.doc<Order(`restaurants/${restaurantId}/orders/${order.id}`)
                       .set(order, { merge: true }));

}

标签: angularunit-testinggoogle-cloud-firestorejasmineangularfire2

解决方案


可能是这样的:


    const AngularFirestoreStub = {
        doc: () => {
          return {
            set: () => {
              // I assume it is a promise because of `from`
              return Promise.resolve(/*... Data you want here */),
            }
          };
        }
    };
 ....
   let afs: any; // declare afs
 ....
    beforeEach(
        async(() => {
           TestBed.configureTestingModule({
               imports: [ RouterTestingModule],
               providers: [{provide: AngularFirestore, useValue: AngularFirestoreStub}]
               declarations: [ AppComponent ]
           }).compileComponents();
        })
    );

afs = TestBed.get(AngularFirestore); // if using Angular 9, this should be .inject instead of .get


it('calls doc with the correct route', async done => {
  // spy on calls to the fireStore.doc and call its actual implementation
  spyOn(afs, 'doc').and.callThrough();
  // call the method and await its response by converting the observable to a promise
  await component.placeOrder({ id: 1 }, 1).pipe(take(1)).toPromise();
  // expect fireStore.doc was called with the right argument
  expect(afs, 'doc').toHaveBeenCalledWith('restaurants/1/orders/1');
  done();
});

检查一下:如何在 Angular 组件中提供/模拟 Angularfirestore 模块以通过默认测试?


推荐阅读