【问题标题】:Angular Material 2 - Trigger change event in md-checkbox in a Unit TestAngular Material 2 - 在单元测试中触发 md-checkbox 中的更改事件
【发布时间】:2017-07-06 04:32:05
【问题描述】:

我在使用 Angular CLI 提供的测试框架设置触发 Angular 单元测试中的 md 复选框的“更改”事件时遇到问题。

我有一个简单的组件:

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>

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

测试代码:

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

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

谢谢。

【问题讨论】:

    标签: javascript angular typescript karma-jasmine angular-cli


    【解决方案1】:

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

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

    应该做的伎俩

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

    【讨论】:

    • 感谢工作 - 我还能够执行以下操作:de = fixture.debugElement.query(By.css('#id label'));
    • 我个人会避免使用 ID,因为在某些情况下您最终可能会得到很多 ID,但是是的,我也为此摸不着头脑。很高兴它起作用了
    • 什么?那么如果输入元素在材质库创建之前不存在,那么如何在模板中绑定事件呢?
    • 你像往常一样把它们放在&lt;md-ckeckbox&gt; 中,这篇文章回答了如何从单元测试中模拟鼠标点击
    猜你喜欢
    • 2017-12-15
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2015-10-08
    • 1970-01-01
    • 2016-07-08
    • 2020-11-25
    相关资源
    最近更新 更多