簡體   English   中英

如何對 Angular2 中的復選框進行單元測試

[英]How to unit test the checkbox in 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 對此進行單元測試?

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

是否需要編寫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();
  ...

ngModel 指令是異步指令,需要使用 Angular 單元測試的異步功能。 添加 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);
  });
}));

源鏈接鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM