簡體   English   中英

重構 Observable 以避免類型斷言錯誤

[英]Refactor Observable to avoid type assertion errors

我正在為CanDeactive Guard 編寫單元測試,並且我的 jasmine 規范出現類型斷言錯誤:

// Mock Guard defined at top of spec file
class MockGuardComponent implements ComponentCanDeactivate {
  // Set this value to the value you want to mock being returned from 
GuardedComponent
  returnValue: boolean | Observable<boolean>;

  canDeactivate(): boolean | Observable<boolean> {
    return this.returnValue || this.openConfirmDialog();
  }
}

it('will not route if guarded and user rejected the dialog', () => {
    // Mock the behavior of the MockGuardedComponent
    const subject$ = new Subject<boolean>();
    mockGuardComponent.returnValue = subject$.asObservable();
    const canDeactivate$ = <Observable<boolean>>(
      service.canDeactivate(mockGuardComponent)
    );
    canDeactivate$.subscribe((deactivate) => {
      // this is the real test
      expect(deactivate).toBeFalsy();
    });
    // Emulate the reject
    subject$.next(false);

}。 );

該規范正確地引發了以下錯誤:

Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead.

它不喜歡這部分:

<Observable<boolean>>

我知道使用BehaviorSubject可能會更好,但我已經在使用Subject ,所以我不確定如何結合我在這里所做的事情。 有小費嗎?

改變

const canDeactivate$ = <Observable<boolean>>(
      service.canDeactivate(mockGuardComponent)
    );

const canDeactivate$ = service.canDeactivate(mockGuardComponent) as Observable<boolean>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM