如何模拟angular2平台浏览器标题组件进行测试

如何模拟angular2平台浏览器标题组件进行测试,angular,karma-jasmine,angular2-testing,Angular,Karma Jasmine,Angular2 Testing,我正在用Jasmine为Angular 2组件编写单元测试。当我的组件被实例化时,我想测试我的文档标题是否被设置为一个特定的值 这是我的组件 import { Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; @Component({ selector: 'cx-account', templateUrl: 'app/account/account.compo

我正在用Jasmine为Angular 2组件编写单元测试。当我的组件被实例化时,我想测试我的文档标题是否被设置为一个特定的值

这是我的组件

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调试运行程序”应为“帐户”


我终于找到了解决问题的办法。我使用测试床来获得我注入的服务。然后使用该服务获取当前测试上下文中的页面标题。 这是我的新代码

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');
    });


});

请记住,您不需要像示例语法那样提供它:
提供程序:[{provide:Title,useClass:Title}]
。仅仅是常规的
提供者:[Title]
就足够了。