我正在尝试测试一个返回可观察值并调用另一个函数的身份验证防护。我的守卫看起来像这样(摘自托德座右铭。干杯托德):
@Injectable()
export class ProductSummaryLoadedGuard implements CanActivate {
constructor(private store: Store<fromProductStore.State>) {}
canActivate(): Observable<boolean> {
return this.checkStore().pipe(
switchMap(() => of(true)),
catchError(() => of(false))
);
}
checkStore(): Observable<boolean> {
return this.store.pipe(select(fromProductStore.selectProductLoaded)).pipe(
tap(loaded => {
if (!loaded) {
this.store.dispatch(new fromProductStore.LoadProductSummary());
}
}),
filter(loaded => loaded),
take(1)
);
}
}
我已经为此整理了规范的框架,导致问题的摘录如下:
it('should return true when checkStore() returns true', () => {
spyOn(guard, 'checkStore').and.returnValue(of(true));
const result = guard.canActivate();
expect(result).toBeObservable(of(true));
});
执行此规范时,我在 Karma 中遇到此错误:
TypeError: Cannot read property 'indexOf' of undefined at Function.TestScheduler.parseMarbles (./node_modules/rxjs/_esm5/internal/testing/TestScheduler.js?:243:21)
我在这里缺少什么?我不想仅针对这一种方法使用弹珠测试,但如果有人可以建议一种方法,那么我很乐意尝试!
最佳答案
示例Effect testing来自 NgRx 的代码显示使用 toBeObservable 因此:
const expected = hot('-------a', {
a: {
type: '[Customers API] Search Customers Success',
customers: [...],
},
});
expect(
effects.searchCustomers$({
debounce: 20,
scheduler: getTestScheduler(),
})
).toBeObservable(expected);
.toBeObservable()
需要一个 TestHotObservable
或 TestColdObservable
,它们具有 marbles
属性。我来到这里是因为我收到错误 TypeError: Cannot read property 'marbles' of undefined
by using .toBeObservable()
with noparameters。
如果您想使用非 TestXXXObservable
类型的可观察量进行测试,则必须订阅它们并在订阅中验证结果为 NgRx testing example显示:
// create an actions stream and immediately dispatch a GET action
actions$ = of({ type: '[Customers Page] Get Customers' });
// mock the service to prevent an HTTP request
customersServiceSpy.getAllCustomers.and.returnValue(of([...]));
// subscribe to the Effect stream and verify it dispatches a SUCCESS action
effects.getAll$.subscribe(action => {
expect(action).toEqual({
type: '[Customers API] Get Customers Success',
customers: [...],
});
});
关于Angular:测试返回可观察值的守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53211591/