2017-01-10 63 views
8

我使用angular2創建了一個登錄頁面。它有兩個輸入字段,分別爲userNamepassword。該登錄中有一個按鈕。 當我要爲loginComponent編寫測試用例時,必須使用predicate來識別button。這是我的測試用例。如何在angular2中使用謂詞

import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 
import { By } from '@angular/platform-browser'; 
import { DebugElement } from '@angular/core'; 
import { LoginComponent } from './login.component'; 


export class LoginComponentTest { 
    constructor(public loginComponent: LoginComponent){ 
    this.loginComponent.logIn('Chathura', '1234'); 

    } 
} 

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

    const fixture = TestBed.createComponent(LoginComponent); 

    const button = fixture.query(predicate: Predicate<DebugElement>, scope?: Function) : DebugElement 

}); 

我要通過提供輸入值進行測試,然後單擊登錄按鈕,看看接下來會發生什麼。

我無法找到正確使用謂詞的正確教程。

回答

3

創建Predicate的最簡單方法是使用By靜態方法之一,即css,directive

const button = fixture.debugElement.query(By.css('.the-button')).nativeElement; 

By.css讓我們來通過任何css選擇器。 query的結果將爲DebugElement,因此如果您想與本機DOM元素進行交互,則需要獲取nativeElement

+0

我知道使用'By.css('。-button')'但問題是,如果有一組按鈕,很難識別每個按鈕。那我們該怎麼辦?更好的是,如果有一個函數調用'id'。 – hennamusick

+1

使用需要使用正確的選擇器。你知道如何使用CSS選擇特定的按鈕?這是基本的CSS東西。與Angular無關。 'css'方法可以帶任何css選擇器。如果你不確定如何去做,那麼你可以讓它更容易,只需給按鈕一個ID。然後你可以做'css('#button-id')' –

+0

謝謝。這是工作。 – hennamusick