Angular Material 2 - 在单元测试中触发 md-checkbox 中的更改事件

2023-12-12

我在使用 Angular CLI 提供的测试框架设置触发 Angular 单元测试中 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;
  }
}

模板:

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

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

Thanks.


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

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

应该能解决问题

您也可以仅导入MdCheckbox模块而不是材质模块。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular Material 2 - 在单元测试中触发 md-checkbox 中的更改事件 的相关文章