【问题标题】:How to unit test the checkbox in Angular2如何对Angular2中的复选框进行单元测试
【发布时间】:2017-05-13 23:07:26
【问题描述】:

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

【问题讨论】:

    标签: unit-testing angular checkbox karma-jasmine


    【解决方案1】:

    组件,例如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
    });
    });
    

    【讨论】:

      【解决方案2】:

      有必要写fixture.detectChanges()吗?

      我在没有这个的情况下进行了相同的测试,并以成功告终。 默认情况下,按钮 1 为“选中”

        const button1 = debugElement.nativeElement.querySelector(selectorBtn1);
        const button2 = debugElement.nativeElement.querySelector(selectorBtn2);
        ...
        expect(button1.checked).toBeTruthy();
        expect(button2.checked).toBeFalsy();
      
        button2.click();
      
        expect(button1.checked).toBeFalsy();
        expect(button2.checked).toBeTruthy();
        ...
      

      【讨论】:

        猜你喜欢
        • 2017-01-21
        • 2016-03-13
        • 2017-04-14
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 2012-01-08
        • 2012-08-25
        • 2019-11-02
        相关资源
        最近更新 更多