我如何模拟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 }));
}发布于 2020-04-05 15:53:55
可能是这样的:
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();
});看看这个:How to provide/mock Angularfirestore module inside angular component for default test to pass?
https://stackoverflow.com/questions/61040877
复制相似问题