2016-11-17 95 views
1

我正在嘗試做angular2測試並遇到問題。我正在嘗試在HTML中測試綁定。簡要的代碼如下所示:Angular 2測試組件html

組件:

export class NavbarComponent { 
    projectName = "Quiz!" 
} 

模板:

<a class="navbar-brand" routerLink="/intro">{{projectName}}</a> 

我一直努力遵循在線的例子,我已經嘗試過這樣做的以下幾個方面:

describe('NavBar component',() => { 
    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      declarations: [NavbarComponent], 
     }); 
    }); 
}); 

it('should contain the projectName variable',() => { 
    let fixture = TestBed.createComponent(NavbarComponent); 
    fixture.detectChanges(); 

    let nav = fixture.nativeElement 
    let title = nav.querySelectorAll('.navbar-brand'); 

    expect(title.textContent).toContain(nav.projectName); 
}); 

該方法給出此錯誤:錯誤:無法創建組件NavbarComponent因爲它沒有被導入到測試模塊中!

我曾嘗試第二種方法:

let fixture: ComponentFixture<NavbarComponent>; 
let component: NavbarComponent; 
let debug: DebugElement; 
let element: HTMLElement; 

describe('NavBarComponent',() => { 
    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      declarations: [NavbarComponent] 
     }); 
    }); 

    fixture = TestBed.createComponent(NavbarComponent); 
    component = fixture.componentInstance; 

    debug = fixture.debugElement.query(By.css('.navbar-brand')); 
    element = debug.nativeElement 

}); 

describe('navbar title check, project name variable', function() { 
    it('should be Quiz!', function() { 
     fixture.detectChanges(); 
     expect(element.textContent).toContain(component.projectName); 
    }); 
}); 

對於這種方法,我得到以下錯誤:類型錯誤:無法讀取的不確定

財產「detectChanges」我是新來的編程更不用說測試,所以任何幫助將不勝感激。謝謝

+0

您是否在測試文件中使用了'filepath'中的導入{NavbarComponent} – Anil

回答

0

把所有東西都放入describe,擺脫第二個describe並把it放在第一個裏面。同時所有的任務應該去beforeEach

describe('',() => { 
    let someVar; 

    beforeEach(() => { 
    TestBed.configureTestingModule({}); 
    someVar = whatever; 
    }) 

    it('',() => { 

    }) 
}) 

這應該讓你開始內部。