可观察以避免类型断言错误

问题描述 投票:0回答:1

我正在编写CanDeactive Guard的单元测试,并且我的茉莉花规格出现类型声明错误:

// 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,所以我不确定如何结合我在这里所做的事情。有小费吗?

angular jasmine
1个回答
1
投票

更改

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

收件人

const canDeactivate$ = service.canDeactivate(mockGuardComponent) as Observable<boolean>;
© www.soinside.com 2019 - 2024. All rights reserved.