用于Promise的Jasmine间谍程序设置为可观察式

时间:2018-10-24 08:41:02

标签: angular jasmine testbed spyon

我正在为Angular编写一个单元测试用例,以供使用Jasmine封装可观察的调用。我无法嘲笑这个诺言以便对其进行测试。

组件

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.of进行设置时被调用。但是communicationService的校准未发生,因为它已在Promise中解决。

有人能帮助我模拟我需要测试诺言和可观察组合的东西吗?

0 个答案:

没有答案