Angular Jasmine test : Expected a spy, but got undefined

Viewed 403

I am using material dialog in angular and writing test to test close of the dialog I am getting error Expected a spy, but got undefined. Getting error in test fit('should call the function to close the dialog'

describe('XYZDetailsComponent', () => {
  let component: XYZDetailsComponent;
  let fixture: ComponentFixture<XYZDetailsComponent>;

  const data = {
    ip: '1.1.1.1',
    name: 'test'
 }

  const setupComponent = () => {
    fixture = TestBed.createComponent(XYZDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  };

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, MatDialogModule ],
      declarations: [XYZDetailsComponent],

      providers: [
        { provide: MatDialogRef, useFactory: () => jasmine.createSpyObj('MatDialogRef', ['close', 'afterClosed']) },
        {provide: MAT_DIALOG_DATA, useValue: data},
       ]
    })
    .compileComponents();
  });

  it('should create', () => {
    setupComponent();
    expect(component).toBeTruthy();
  });

  fit('should call the function to close the dialog', () => {
    setupComponent();
    component.onNoClick();
    expect(component.dialogRef.close()).toHaveBeenCalled();
  });
});
1 Answers

I think you need to get a handle on the MatDialogRef from the outside (from the test) and not from the component.

Try this and please replace anys with your types:

describe('XYZDetailsComponent', () => {
  let component: XYZDetailsComponent;
  let fixture: ComponentFixture<XYZDetailsComponent>;
  // add this line
  let mockDialogRef: jasmine.SpyObj<any>;

  const data = {
    ip: '1.1.1.1',
    name: 'test'
 }

  const setupComponent = () => {
    fixture = TestBed.createComponent(XYZDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  };

  beforeEach(() => {
    // assign the variable to spy object before each test
    // This ensures we get fresh spies for each test
    mockDialogRef = jasmine.createSpyObj('MatDialogRef', ['close', 'afterClosed']);
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, MatDialogModule ],
      declarations: [XYZDetailsComponent],

      providers: [
        // modify this line
        { provide: MatDialogRef, useValue: mockDialogRef ,
        {provide: MAT_DIALOG_DATA, useValue: data},
       ]
    })
    .compileComponents();
  });

  it('should create', () => {
    setupComponent();
    expect(component).toBeTruthy();
  });

  fit('should call the function to close the dialog', () => {
    setupComponent();
    component.onNoClick();
    // alter this line
    expect(mockDialogRef.close).toHaveBeenCalled();
  });
});
Related