角度材料2 - 单元测试中md复选框中的触发器更改事件

the*_*man 1 javascript typescript karma-jasmine angular-cli angular

我在使用Angular CLI提供的测试框架设置时,在角度单元测试中触发md-checkbox的"更改"事件时遇到问题.

我有一个简单的组件:

TS:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  checkedValue = 'false';

  result = false;

  checkValueChange(event) {
    console.log('CheckBox clicked: ' + event.checked);
    this.result = true;
  }
}
Run Code Online (Sandbox Code Playgroud)

模板:

<md-checkbox [checked]="true" [(ngModel)]="checkedValue" (change)="checkValueChange($event)">Check Box</md-checkbox>
Run Code Online (Sandbox Code Playgroud)

以下是我试图通过模拟点击发出更改事件的单元测试代码:

测试代码:

import {TestBed, async, fakeAsync} from '@angular/core/testing';
import { AppComponent } from './app.component';
import {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';
import {MaterialModule} from '@angular/material';
import {FormsModule} from '@angular/forms';
import {tick} from '@angular/core/testing';

let de:      DebugElement;
let el:      HTMLElement;

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [MaterialModule, FormsModule]
    }).compileComponents();
  }));

  it('should create the app', fakeAsync(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;

    de = fixture.debugElement.query(By.css('md-checkbox'));
    el = de.nativeElement;

    // Neither click appears to trigger the change event to occur, or update the model
    de.triggerEventHandler('click', {});
    el.click();

    tick(100);
    expect(app.result).toBe(true);
  }));
});
Run Code Online (Sandbox Code Playgroud)

所以也许尝试通过点击触发更改事件是不正确的?有人有任何想法吗?

谢谢.

Son*_*300 6

句柄不在md-checkbox中,而是在其label元素中

de = fixture.debugElement.query(By.css('md-checkbox label'));
el = de.nativeElement;
el.click();
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩

您也可以只导入MdCheckboxModule而不是MaterialModule.