2016-09-28 5 views
3

Jasmine을 사용하여 Angular 2 구성 요소의 단위 테스트를 작성하고 있습니다. 구성 요소가 인스턴스화 될 때 내 문서 제목이 특정 값으로 설정되었는지 테스트하고 싶습니다.angular2 platform-browser를 모의하는 방법 테스트 용 제목 구성 요소

은 여기 내 구성 요소 I 테스트를 위해 쓴하지만이 작동하지 않는 것을 여기

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() 날 카르마 디버그 러너 페이지 제목을 제공합니다.

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

카르마 출력은 : 나는 마침내 내 문제에 대한 해결책을 발견

Error: Expected 'Karma DEBUG RUNNER' to be 'Account'.

답변

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


}); 
관련 문제