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:
import { TestBed } from '@angular/core/testing';
import { TerrainShopResolverService } from './terrain-shop-resolver.service';
import { PLATFORM_ID } from '@angular/core';
import { TerrainShopService } from './terrain-shop.service';
import { Observable } from 'rxjs';
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
:
let platformId = 'server';
The next step is to prepare a mock of TerrainShopService
:
let timeout = 1000;
let terrainServiceMock = {
getPromotions() {
return new Observable((observer) => {
setTimeout(() => {
observer.next(['testValue']);
observer.complete();
}, timeout);
});
},
};
This page is a preview of The newline Guide to Angular Universal