14

I am writing unit tests for Angular 2 component with Jasmine. I would like to test if my document title has been set to a specific value when my component is instantiated.

Here is my component

import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Component({
  selector: `cx-account`,
  templateUrl: `app/account/account.component.html`,
})
export class AccountComponent {
  public constructor(titleService: Title) {
    titleService.setTitle(`Account`);
  }
}

Here what I have written for testing, but it is not working. titleService.getTitle() gives me Karma debug runner page title.

import { TestBed } from '@angular/core/testing';
import { Title } from '@angular/platform-browser';
import { AccountComponent } from './account.component';

describe(`AppComponent`, () => {
  const titleService: Title = new Title();

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AccountComponent],
      providers: [{ provide: Title }],
    });
  });

  it(`Title should be "Account"`, () => {
    expect(titleService.getTitle()).toBe(`Account`);
  });
});

Karma output is :

Error: Expected 'Karma DEBUG RUNNER' to be 'Account'.

C0ZEN
  • 894
  • 11
  • 41
Aristo
  • 313
  • 2
  • 12

1 Answers1

16

I finally found a solution to my problem. I used the TestBed to get the service I have injected. Then use that service to get the page Title in the current Test context. Here is my new Code

import { TestBed } from '@angular/core/testing';
import { Title } from '@angular/platform-browser';
import { AccountComponent } from './account.component';

describe(`AccountComponent`, () => {
  let titleService: Title;
  let fixture: any;
  let component: AccountComponent;

  beforeEach(async (() => {
    TestBed.configureTestingModule({
      declarations: [AccountComponent],
      providers: [Title],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AccountComponent);

    // Access the dependency injected component instance
    component = fixture.componentInstance;
  });

  it(`should instantiate component`, () => {
    expect(component instanceof AccountComponent).toBe(true, `should create AccountComponent`);
  });

  it(`Page title should be "Account"`, () => {
    titleService = TestBed.get(Title);

    expect(titleService.getTitle()).toBe(`Account`);
  });
});
C0ZEN
  • 894
  • 11
  • 41
Aristo
  • 313
  • 2
  • 12
  • 4
    Keep in mind you don't need to provide it like example syntax: `providers: [{ provide: Title, useClass: Title }]`. Just regular `providers: [Title]` is totally enough. – magos Nov 21 '18 at 09:21