首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度:测试返回可观测值的防护装置。

角度:测试返回可观测值的防护装置。
EN

Stack Overflow用户
提问于 2018-11-08 16:02:49
回答 1查看 1.5K关注 0票数 2

我正在尝试测试一个返回一个可观察到的,并调用另一个函数的auth守卫。我的警卫看起来像这样(从托德的座右铭中解放出来)。(干杯托德):

代码语言:javascript
复制
@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)
    );
  }
}

为此,我将规范的骨架组合在一起,导致问题的摘录如下:

代码语言:javascript
复制
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中遇到了这个错误:

(./node_modules/rxjs/_esm5/internal/testing/TestScheduler.js?:243:21):无法读取未定义的属性“indexOf”在Function.TestScheduler.parseMarbles Function.TestScheduler.parseMarbles

我在这里错过了什么?我不想只为这一种方法使用大理石测试,但如果有人能建议一种方法,那么我会很高兴尝试它!

EN

回答 1

Stack Overflow用户

发布于 2020-04-03 13:18:15

因此,来自NgRx的示例NgRx代码使用toBeObservable显示:

代码语言:javascript
复制
const expected = hot('-------a', {
  a: {
    type: '[Customers API] Search Customers Success',
    customers: [...],
  },
});

expect(
  effects.searchCustomers$({
    debounce: 20,
    scheduler: getTestScheduler(),
  })
).toBeObservable(expected);

.toBeObservable()需要一个具有marbles属性的TestHotObservableTestColdObservable。我之所以来到这里,是因为通过使用没有参数的TypeError: Cannot read property 'marbles' of undefined,我得到了一个.toBeObservable()错误。

如果您想使用非TestXXXObservable类型的可观测数据进行测试,您必须订阅它们并验证订阅中的结果,如NgRx测试实例所示:

代码语言:javascript
复制
// 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: [...],
  });
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53211591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档