如何在Rxjs 6中测试Ngrx管道选择 [英] How to test ngrx pipe select in Rxjs 6

查看:165
本文介绍了如何在Rxjs 6中测试Ngrx管道选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我可以测试以下商店选择

Previously I could test the below store select

this.store.select(fromRoot.someselector).pipe(map(r => this.store.dispatch(new Action())));

这是我的测试

{provide: Store, useValue: jasmine.createSpyObj('store', ['select']);

store.select.and.returnValue(of({}));

但是现在它变成了管道

this.store.pipe(select(fromRoot.someselector));

this.store.pipe(
        select(fromRoot.someselector), 
        filter(result => !!result), 
        map(r => { 
             if (result === ' hello') { 
               this.store.dispatch(new Action()); 
             } 
           }
        ));

如何进行测试,特别是在选择后具有地图并且在其中进行分派动作并希望验证动作被调用时.

How to test this especially when you have map after select and within it you are dispatching an action and you want verify action was called.

推荐答案

跳过运算符并直接测试流的结果:

Skip the operators and test directly the result of the stream :

store
  .pipe(select('selector'))
  .subscribe(val => expect(val).toBe(theMockedValSentToTheSpy))

进一步说明:

  • 创建商店的模拟内容
  • 创造价值的模拟物
  • 在您的模拟商店中返回该模拟值
  • 期待您的组件变量返回模拟值

这给出了:

const mockedValue = { id: 1 };
const storeSubjectMock = new BehaviorSubject(mockedValue);
const mockedStore = {
  pipe: () => storeSubjectMock.asObservable(),
};

// { provide: Sotre, useValue: mockedStore }; in your testbed

it('should return an unaltered value', () => {
  component.variableReferencingStore
    .pipe(select('selector'))
    .subscribe(val => expect(val).toBe(mockedValue))
});

现在的好处是,您可以像这样测试所有运算符.假设您的组件变量为

Now the good thing about that is that you can test all operators like that. Say your component variable is

storeValue$ = this.store.pipe(
  select('selector'),
  map(value => ({ ...value, name: 'customName' }))
)

然后您的测试将更改为

it('should return an altered value with a name property set to customName', () => {
  component.variableReferencingStore
    .pipe(select('selector'))
    .subscribe(val => expect(val).toEqual({ ...mockedValue, name: 'customName'))
});

这篇关于如何在Rxjs 6中测试Ngrx管道选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆