【发布时间】: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