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
:
import { TestBed } from '@angular/core/testing';
import { I18nService } from './i18n.service';
import { PLATFORM_ID } from '@angular/core';
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:
let platformId = 'browser';
Stubbing the window object#
Set up the variables that you are going to use in test expectations:
let windowLanguage = 'en-EN';
let windowCurrency = 'GBP';
Next, set up the spec using Jasmine's describe()
and beforeEach()
methods:
describe('I18nService', () => {
let service: I18nService;
beforeEach(() => {
delete (window as any).navigator.language;
Object.defineProperty(window.navigator, 'language', {
configurable: true,
enumerable: true,
value: windowLanguage,
writable: true,
});
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:
TestBed.configureTestingModule({
providers: [
{ provide: PLATFORM_ID, useFactory: () => platformId },
],
});
The last step in beforeEach()
is to inject the service that you are going to test:
This page is a preview of The newline Guide to Angular Universal