Как имитировать компонент заголовка angular2 платформа-браузер для целей тестирования

Я пишу модульные тесты для компонента Angular 2 с помощью Jasmine. Я хотел бы проверить, установлено ли для моего заголовка документа определенное значение при создании экземпляра моего компонента.

Вот моя составляющая

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(private titleService: Title ) {
    titleService.setTitle("Account");
  }
}

Вот что я написал для тестирования, но это не работает. titleService.getTitle() дает мне заголовок страницы отладчика Karma.

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

describe('AppComponent Tests', function () {
  let titleService: Title = new Title(); 
  beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [AccountComponent],
        providers:    [ {provide: Title } ],      
    });
   let fixture = TestBed.createComponent(AccountComponent);

   });

  it('Title Should be Account', () => {
    expect(titleService.getTitle()).toBe('Account');
  });      
});

Выход кармы:

Ошибка: ожидалось, что Karma DEBUG RUNNER будет «Account».


person Aristo    schedule 28.09.2016    source источник


Ответы (1)


Я наконец нашел решение своей проблемы. Я использовал TestBed, чтобы получить введенную мной услугу. Затем используйте эту службу, чтобы получить заголовок страницы в текущем контексте теста. Вот мой новый код

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

describe('AccountComponent Tests', function () {
    let userService: Title;
    let fixture: any;
    let comp: AccountComponent;
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AccountComponent],
            providers: [{ provide: Title, useClass: Title }],
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(AccountComponent);
        // Access the dependency injected component instance
        comp = fixture.componentInstance;
    });

    it('Page title Should be Account', () => {
            userService = TestBed.get(Title);
            expect(userService.getTitle()).toBe("Account");
    });
    it('should instantiate component', () => {
            expect(comp instanceof AccountComponent).toBe(true, 'should create AccountComponent');
    });


});
person Aristo    schedule 07.10.2016
comment
Имейте в виду, что вам не нужно предоставлять это как пример синтаксиса: providers: [{ provide: Title, useClass: Title }]. Просто обычного providers: [Title] вполне достаточно. - person magos; 21.11.2018