How to mock angular2 platform-browser Title component for testing purpose
Asked Answered
V

1

15

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'.

Velocipede answered 28/9, 2016 at 22:57 Comment(0)
V
17

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`);
  });
});
Velocipede answered 7/10, 2016 at 19:35 Comment(2)
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.Nerval
this also helps to get karma coverage.Pelligrini

© 2022 - 2024 — McMap. All rights reserved.