本文介绍了角度材料2 - 单元测试中md复选框中的触发器更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having problems triggering a 'change' event for a md-checkbox in an Angular Unit Test, using the test framework setup provided by the Angular CLI.

我有一个简单的组件:

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

模板:

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

这是我试图引发更改事件的单元测试代码 - 通过模拟点击:

And here is the unit test code I am trying to cause the change event to be emitted - via a simulated click:

测试代码:

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

因此,尝试通过点击触发更改事件是不正确的?有人有任何想法吗?

So maybe trying to get the change event to trigger via a click is incorrect? Anyone got any ideas?

谢谢。

推荐答案

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

The handle is not in the md-checkbox but in its label element

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

应该做的伎俩

你可以也只导入 MdCheckboxModule 而不是MaterialModule。

You can also import only MdCheckboxModule instead of MaterialModule.

这篇关于角度材料2 - 单元测试中md复选框中的触发器更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 17:16