Unit Tests - long-running API calls

Next step is to simulate a long-running API and verify how server-side Angular deals with it. This lesson will demonstrate you how to do that.

Testing Long-Running API Calls#

Let's now test TerrainShopResolver. This resolver should abandon long-running API calls that may prevent a view from being rendered on the server.

TerrainShopResolver doesn't perform HTTP calls; instead, it delegates them to TerrainShopService. This means you don't need to stub the HttpClient service. You can just mock TerrainShopService and return the data from getPromotions() with a specified delay.

Create a new file, src/app/terrain-shop-resolver.service.spec.ts, and add the following import statements:

Similar to I18nServiceTests, you want to test service behavior both in the browser and on the server. To do this, you are going to provide a mocked PLATFORM_ID value. Declare a variable that will be used to stub PLATFORM_ID:

The next step is to prepare a mock of TerrainShopService:

The code above introduces the terrainServiceMock variable that holds an object containing the getPromotions() method. This method returns an observable that emits after a timeout defined by the timeout variable. You are going to modify this variable in tests.

When mocks are ready, it's time to write the beforeEach() section, inject a service that you are going to test, and verify that it's instantiated correctly:

 

This page is a preview of The newline Guide to Angular Universal

No discussions yet