[英]Refactor Observable to avoid type assertion errors
I'm writing unit tests for a CanDeactive Guard and I'm getting a type assertion error with my jasmine spec:我正在为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);
}. }。 );
);
This spec correctly throws the following error:该规范正确地引发了以下错误:
Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead.
It doesn't like this part:它不喜欢这部分:
<Observable<boolean>>
I understand that it's probably better to use a BehaviorSubject instead but I'm already using a Subject so I'm not sure how to combine what I'm doing here.我知道使用BehaviorSubject可能会更好,但我已经在使用Subject ,所以我不确定如何结合我在这里所做的事情。 Any tips?
有小费吗?
Change改变
const canDeactivate$ = <Observable<boolean>>(
service.canDeactivate(mockGuardComponent)
);
To至
const canDeactivate$ = service.canDeactivate(mockGuardComponent) as Observable<boolean>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.