如何模拟angular2 platform-b​​rowser标题组件以进行测试

Ari*_*sto 9 karma-jasmine angular2-testing angular

我正在使用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");
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我为测试而编写的,但它不起作用.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');
  });      
});
Run Code Online (Sandbox Code Playgroud)

Karma输出是:

错误:预计'Karma DEBUG RUNNER'为'帐户'.

Ari*_*sto 7

我终于找到了解决问题的方法.我使用TestBed来获取我注入的服务.然后使用该服务获取当前Test上下文中的页面Title.这是我的新代码

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


});
Run Code Online (Sandbox Code Playgroud)

  • 请记住,您不需要像示例语法一样提供它:`providers: [{ provide: Title, useClass: Title }]`。只是普通的`providers: [Title]` 就足够了。 (2认同)