angularunit-testingjestjsmat-dialog

How can I test MatDialog.open in a constructor


I have a component that uses inside the constructor dialog open as so :

  dialog = inject( MatDialog );

  constructor () {

    this.dialog.open( WelcomeComponent , {
      width:'350px',
      height:'350px'
    } );

and I don't know how to test if open was called. The problem I'm facing is that the component is created before the jest.spyOn object which leads to 0 calls when trying:

  it( 'open welcome dialog', () => {
    const openDialogSpy = jest.spyOn( TestBed.inject(MatDialog), 'open' );
    expect( openDialogSpy ).toHaveBeenCalled();
    //I know this code leads to nothing but it's just an example
  }) 

EDIT:

Here is my test so far:

import { ElementRef } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { MediaService } from './services/media.service';
import { WelcomeComponent } from './welcome/welcome.component';

describe('AppComponent', () => {

  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports:[AppComponent, NoopAnimationsModule, MatDialogModule ],
      providers:[
        { provide:ElementRef, useValue:{}},
        { provide:MediaService, useValue:{}},
        { provide:MatDialog },
      ]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it( 'open welcome dialog', () => {

    const dialogSpy = jest.spyOn(component.dialog, 'open')
    component.dialog.open( WelcomeComponent , {
      width:'350px',
      height:'350px'
    } );
    expect( dialogSpy ).toHaveBeenCalledTimes(1);

  })

});

Solution

  • Could you try reinitializing the createComponent once you attach the jest spyOn

    it( 'open welcome dialog', () => {
        const dialogSpy = jest.spyOn(component.dialog, 'open')
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        expect( dialogSpy ).toHaveBeenCalledTimes(1);
    
    })