MJP
MJP

Reputation: 75

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:

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

template:

<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(() => {
    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?

Thanks.

Upvotes: 3

Views: 4858

Answers (1)

Sonicd300
Sonicd300

Reputation: 2049

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

should do the trick

You can also import only MdCheckboxModule instead of MaterialModule.

Upvotes: 9

Related Questions