我正在为使用 Jasmine 包装可观察调用的 Promise 编写 Angular 单元测试用例。我无法模拟这个承诺来测试它。
零件
ngOnInit(){
this.getOrder().then(
() => {
this.getShippingAddress();
});
}
private getOrder() {
var promise = new Promise((resolve, reject) => {
this.orderService.getOrder(this.orderOfferId)
.subscribe(
res => {
// This part is not executed from Test
var result: IOrderViewData = this.utilities.resolveJsonReferences(res);
this.viewData = result;
if (this.viewData.orderDate < this.today) {
this.message = "Order cannot be in the past";
}
resolve();
},
err => {
reject();
});
});
return promise;
}
private getShippingAddress() {
return this.communicationService.getShippingAddress(this.orderOfferId);
}
测试
it('Should validate the order date given the date is in past', (done) => {
orderMockViewData.orderDate = new Date(2017,10,22);
let orderSpy = spyOn(orderService, "getOrder").and.returnValue(Observable.of(orderMockViewData));
let addressSpy = spyOn(communicationService, "getShippingAddress").and.returnValue(Observable.of(shippingMockViewData));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(orderSpy).toHaveBeenCalledWith("order/d371abcb-a935-4f85-bcca-baa0bf32e1ac"); // SUCCESS
expect(addressSpy).toHaveBeenCalledWith("address/d371abcb-a935-4f85-bcca-baa0bf32e1ac"); // FAILED
expect(componentInstance.message).toEqual("Order cannot be in the past"); // FAILED
done();
});
});
问题
我可以看到 orderSpy 被调用,因为它是使用 Observable 设置的。的。但是对communicationService 的调用并没有发生,因为它是在promise 中解决的。
有没有人帮助我模拟我需要测试承诺和可观察组合的事情?