如何对Angular2中的复选框进行单元测试 [英] How to unit test the checkbox in Angular2

查看:66
本文介绍了如何对Angular2中的复选框进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Angular2编写的复选框示例代码.

I have a sample code for checkbox written with 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进行单元测试?

I want to unit test the above checkbox. Like I want to recognize the checkbox and test whether it is check-able. How do I unit test this with Karma Jasmine?

推荐答案

组件,例如CheckboxComponent,包含输入元素.单元测试应类似于:

Component, e.g. CheckboxComponent, contains input element. Unit test should looks like:

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

这篇关于如何对Angular2中的复选框进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆