angularjasmineangular-unit-test

How to Unit Test MatBottomSheet


I am getting an error that DependentComponent's properties are not set.

I want to ignore calling DependentComponent - this._bottomSheet.open(DependentComponent), but not sure how to achieve that.

I guess mockBottomSheetRef.open.and.callThrough(); is not the correct way of doing this. I need help here.

.ts


constructor(private _bottomSheetRef: MatBottomSheetRef<DependentComponent>) { }

showOverlay() {
    this._bottomSheet.open(DependentComponent, {
      panelClass: 'search-container'
    });
 }

spec.ts

  mockBottomSheetRef = { open: jasmine.createSpy('open') };

  TestBed.configureTestingModule({
    declarations: [
      MyComponent
      DependentComponent
    ],
    imports: [
      TestModule
    ],
    providers: [
      { provide: MatBottomSheetRef, useValue: mockBottomSheetRef }
    ],
  })
  .overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [DependentComponent] } })
  .compileComponents();



  it('should', () => {
    mockBottomSheetRef.open.and.callThrough(); 
    component.showOverlay();
    expect(mockBottomSheetRef.open).toHaveBeenCalled();
  });

Solution

  • typo is the worst bug :D

    this._bottomSheet.open - it is MatBottomSheet while the mock provided for the MatBottomSheetRef. notice the Ref in the end.

    It should work like this:

      mockBottomSheet = { open: jasmine.createSpy('open') };
    
      TestBed.configureTestingModule({
        declarations: [
          MyComponent
          DependentComponent
        ],
        imports: [
          TestModule
        ],
        providers: [
          { provide: MatBottomSheet, useValue: mockBottomSheet }
        ],
      })
      .overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [DependentComponent] } })
      .compileComponents();
    
    
      it('opens bottom sheet when `showOverlay` executed', () => {
        component.showOverlay();
        expect(mockBottomSheet.open).toHaveBeenCalled();
      });