Angular Material 2 - Trigger change event in md-checkbox in a Unit Test

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.

I have a simple component:


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

  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:

test code:

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(() => {
      declarations: [
      imports: [MaterialModule, FormsModule]

  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', {});;


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




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

should do the trick

You can also import only MdCheckboxModule instead of MaterialModule.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.