0

I am writing karma/jasmine test case for the click event, but I am getting null for button. Please suggest me. Thanks in Advance.

  it('should', async(() => {
    spyOn(component, 'clickMethod');
    let button = fixture.debugElement.nativeElement.querySelector('#view-rec');
    console.log(button); --> button is null I am getting
    button.click();
    fixture.whenStable().then(() => {
        expect(component.clickMethod).toHaveBeenCalled();
    })

component::

  clickMethod() {
      this.msg.node.setVal(false);
      this.myBtn = "Hello";
  }

Html::

<mat-menu #menu="matMenu" class="dropdown">
  <button mat-menu-item>
  </button>
  <button mat-menu-item id="view-rec"(click)='clickMethod()'>   
  </button> 
</mat-menu>
Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
YYY
  • 3,440
  • 5
  • 20
  • 24

1 Answers1

1

I think you need to open the menu 1st, and then you'll get access to the mat-menu-item which you want to click.

For example:

<button id="menu-open-icon" mat-icon-button [matMenuTriggerFor]="menu"> 
  <mat-icon>more_vert</mat-icon>
</button>

<mat-menu #menu="matMenu"> 
  <button mat-menu-item id="view-rec"(click)='clickMethod()'>
    <mat-icon>dialpad</mat-icon>
    <span>Redial</span>
  </button>
  <button mat-menu-item disabled>
    <mat-icon>voicemail</mat-icon>
    <span>Check voicemail</span>
  </button>
  <button mat-menu-item>
    <mat-icon>notifications_off</mat-icon>
    <span>Disable alerts</span>
  </button>
</mat-menu>

try:

it('should', () => {
    spyOn(component, 'clickMethod').and.callThrough();
    let menuIcon = fixture.debugElement.nativeElement.querySelector('#menu-open-icon')
    menuIcon.click();
    let button = fixture.debugElement.nativeElement.querySelector('#view-rec');
    console.log(button); --> this should not be null now
    button.click();
    fixture.detectChanges();
    expect(component.clickMethod).toHaveBeenCalled()
})
Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
  • @Vivek Thanks, I got it. – YYY Nov 03 '20 at 18:00
  • @Vivek, I am able to get button details with id="menu-open-icon". but I am unable to get the button with id="view-rec", because of mat-menu is loading dynamically from other component. please suggest me, how to get the dynamic loading button details. – YYY Nov 05 '20 at 11:05
  • @YYY : sure, can u please add more HTML code to help me understand. Also , any comments for https://stackoverflow.com/questions/64678832/how-to-create-stubs-for-karma-jasmine-testing-in-angular/64680431#64680431 ? – Shashank Vivek Nov 05 '20 at 15:34