【问题标题】:Refactor Observable to avoid type assertion errors重构 Observable 以避免类型断言错误
【发布时间】:2021-02-23 02:27:20
【问题描述】:

我正在为 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 所以我不确定如何结合我正在做的事情这里。有什么建议吗?

【问题讨论】:

  • 重构你的代码,让canDeactivate总是返回Observable

标签: angular jasmine


【解决方案1】:

改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多