如何对 MatBottomSheet 进行单元测试

时间:2021-07-27 08:10:22

标签: angular jasmine angular-unit-test

我收到一个错误,提示未设置 DependentComponent 的属性。

我想忽略调用 DependentComponent - this._bottomSheet.open(DependentComponent),但不确定如何实现。

我猜 mockBottomSheetRef.open.and.callThrough(); 不是这样做的正确方法。我需要帮助。

.ts


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

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

规格

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

1 个答案:

答案 0 :(得分:2)

打字错误是最糟糕的错误 :D

this._bottomSheet.open - 它是 MatBottomSheet,而模拟为 MatBottomSheetRef 提供。注意最后的 Ref

它应该是这样工作的:

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