2016-12-29 40 views
2

我有用Angular2編寫的複選框的示例代碼。如何在Angular2中對複選框進行單元測試

<div class="col-sm-7 align-left" *ngIf="Some-Condtion"> 
    <input type="checkbox" id="mob_Q1" value="Q1" /> 
    <label for="mob_Q1">Express</label> 
</div> 

我想單元測試上面的複選框。就像我想識別複選框並測試它是否可檢查一樣。我如何用Karma Jasmine對此進行測試?

回答

3

成分,例如CheckboxComponent包含輸入元素。單元測試應該看起來像:

import {ComponentFixture, TestBed} from '@angular/core/testing'; 
import {By} from '@angular/platform-browser'; 
import {CheckboxComponent} from './checkbox.component'; 

describe('Checkbox test.',() => { 

let comp: CheckboxComponent; 
let fixture: ComponentFixture<CheckboxComponent>; 
let input: Element; 

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

    fixture = TestBed.createComponent(CheckboxComponent); 
    comp = fixture.componentInstance; 
    input = fixture.debugElement.query(By.css('#mob_Q1')).nativeElement; 
}); 

it('should click change value',() => { 
    expect(input.checked).toBeFalsy(); // default state 

    input.click(); 
    fixture.detectChanges(); 

    expect(input.checked).toBeTruthy(); // state after click 
}); 
}); 
相關問題