简体   繁体   English

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

[英]How to unit test the checkbox in Angular2

I have a sample code for checkbox written with 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>

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?我如何使用 Karma Jasmine 对此进行单元测试?

Component, eg CheckboxComponent, contains input element. 组件,例如CheckboxComponent,包含input元素。 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
});
});

IS there a need to write fixture.detectChanges() ? 是否需要编写fixture.detectChanges()

I went through the same test without this and it ends with success. 没有这个,我经历了相同的测试,并以成功结束。 Button 1 is 'checked' by default 默认情况下,“检查”按钮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();
  ...

ngModel directive is async one and requires to use asynchronous capabilities of Angular unit testing. ngModel 指令是异步指令,需要使用 Angular 单元测试的异步功能。 Adding async and whenStable functions.添加 async 和 whenStable 函数。

it('checkbox is checked if value is true', async(() => {
  component.model = true;
  fixture.detectChanges();

  fixture.whenStable().then(() => {
    const inEl = fixture.debugElement.query(By.css('#mob_Q1'));
    expect(inEl.nativeElement.checked).toBe(true);
  });
}));

Source Link Link 源链接链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM