An example of spyOn used in Angular unit test

There is an Observable array in the Component to be tested:

Assign value by the following code:

this.checkoutDeliveryService.getSupportedDeliveryModes();

The type of checkoutDeliveryService: CheckoutDeliveryService

In the unit test, we need to isolate the actual implementation of CheckoutDeliveryService by creating a MockCheckoutDeliveryService.

First create an instance of mockcheckoutDeliveryService in the unit test:

Create a MockCheckoutDeliveryService class:

class MockCheckoutDeliveryService {
  loadSupportedDeliveryModes = createSpy();
  setDeliveryMode = createSpy();
  getSupportedDeliveryModes(): Observable<DeliveryMode[]> {
    return of();
  }
  getSelectedDeliveryMode(): Observable<DeliveryMode> {
    return of();
  }
  getLoadSupportedDeliveryModeProcess(): Observable<LoaderState<void>> {
    return of();
  }
}

The method is the same as the real CheckoutDeliveryService class method, the difference is that it returns an empty Observable object.

In the provider configuration of TestBed.configureTestingModule, use class MockCheckoutDeliveryService to inject CheckoutDeliveryService:

Get an instance of mockCheckoutDeliveryService through TestBed.inject:

Use the spyOn code to set the return value of the getSupportedDeliveryModes method of the mockCheckoutDeliveryService class to of(mockSupportedDeliveryModes):

In this way, when the unit test is executed, when the Component calls the getSupportedDeliveryModes method of checkoutDeliveryService, it will automatically return the value we specified in spyOn.

For more original articles by Jerry, please follow the public account "Wang Zixi":

Guess you like

Origin blog.csdn.net/i042416/article/details/109093037