重构 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>;
我正在为 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>;