首页 文章

如何对Angular2中的复选框进行单元测试

提问于
浏览
3

我有一个用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进行单元测试?

1 回答

  • 5

    组件,例如CheckboxComponent,包含input元素 . 单元测试应如下所示:

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

相关问题