【问题标题】:How to mock angular2 platform-browser Title component for testing purpose如何模拟 angular2 平台浏览器标题组件以进行测试
【发布时间】:2016-09-28 22:57:46
【问题描述】:

我正在使用 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 DEBUG RUNNER”应为“帐户”。

【问题讨论】:

    标签: angular karma-jasmine angular2-testing


    【解决方案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');
        });
    
    
    });
    

    【讨论】:

    • 请记住,您不需要像示例语法那样提供它:providers: [{ provide: Title, useClass: Title }]。只是普通的providers: [Title] 就足够了。
    猜你喜欢
    • 2012-05-17
    • 2010-12-28
    • 1970-01-01
    • 2016-06-28
    • 2017-06-18
    • 1970-01-01
    • 2012-08-03
    • 2011-10-26
    相关资源
    最近更新 更多