1

I am writing Angular a unit test case for a promise that wraps the observable call using Jasmine. I am not able to mock this promise in order to test it.

Component

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);
}

Test

    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();
        });

    });

Problem

I could see orderSpy is getting called as it was setup using Observable. of. But the call to the communicationService does not happen as it was resolved in a promise.

Does anyone help me on how to mock such things as I need to test promise and observable combination?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Developer
  • 487
  • 9
  • 28
  • Is it possible it is getting stuck in the this.utilities.resolveJsonReferences() call? I don't see a spy preventing that call from being executed. I would try spying on that with some reasonable data returned for your result variable and see if that is what's going on. – dmcgrandle Oct 25 '18 at 01:16
  • @dmcgrandle that is not a problem. `this.utilities.resolveJsonReferences` accepts and returns the same value by checking helper function. I already verified by placing console.log in the previous line and it did not reach. – Developer Oct 26 '18 at 11:32

0 Answers0