Unit Tests - Stubbing PLATFORM_ID

How to verify your application behavior in different environments? In this lesson you will get to know how you can stub the PLATFORM_ID injection token and HTTP request, for tests purpose.

Stubbing PLATFORM_ID#

Let's start by testing I18nService. As you may recall, this service determines the user's language and prints currency in the corresponding format. It injects the PLATFORM_ID token from the @angular/core library. The token is used in the isPlatformBrowser() method, determining if the code executes on the server or in the browser.

Create a new file, src/app/i18n.service.spec.ts, then import TestBed and I18nService:

What is PLATFORM_ID?#

The value held by the variable identified with the PLATFORM_ID token is a string. That string has the value browser or server depending on where code executes. You can stub it as a variable reference. Add the following code to the test file:

Stubbing the window object#

Set up the variables that you are going to use in test expectations:

Next, set up the spec using Jasmine's describe() and beforeEach() methods:

The code above introduces a mechanism that changes the value of window.navigator.language to the value of the windowLanguage variable before each test.

You can now provide the PLATFORM_ID token with the TestBed.configureTestingModule() method:

The last step in beforeEach() is to inject the service that you are going to test:

At this point, your code containing import statements and the beforeEach() method should look like the following:

 

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

No discussions yet