如何对 MatBottomSheet 进行单元测试

How to Unit Test MatBottomSheet

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

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

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

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

打字错误是最严重的错误:D

this._bottomSheet.open - 它是 MatBottomSheet 而 mock 是为 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();
  });