繁体   English   中英

如何做一个简单的 angular Jasmine 单元测试时使用 RXJS 使用主题的反应方法和调用服务的 stream

[英]How to do a simple angular Jasmine Unit testing when using RXJS reactive approach using a subject and a stream that calls a service

使用 RXJS 反应式方法时,如何进行简单的 angular Jasmine 单元测试

这是我对该组件的简单实现。 我有一个项目 stream 可以收集一些项目。 然后我在 HTML 中有一个下拉菜单调用 onSelectItem 方法,该方法触发 selectedItemSubject 的 next() 方法。 我的目标是测试 $itemsWithSelected stream - 检查它是否返回正确的值 - 这受所选项目和项目 stream 的影响。

  items$ = this.someService.getItems().pipe(
    map((items) => {
      return items;
    })
  );

  private selectedItemSubject$ = new Subject<any>();
  selectionItemAction$ = selectedItemSubject$.asObservable();

  $itemsWithSelected = combineLatest([this.selectionItemAction$, items$]).pipe(
    map(([selected, items]) => {
      var targetItem = items.find(x => x.id === selected);
    return someProcess(targetItem.someProperyOfThisItem);
    }));

  //some method that calls next of the subject
  onSelectItem($event){
    this.selectedItemSubject$.next($event.value);
  }

要检查$itemsWithSelected发出的值,您可以链接 pipe 并点击发出的值:

$itemsWithSelected = combineLatest([this.selectionItemAction$, items$])
        .pipe(
            tap(([selected, items]) => {
                // check the emitted value here
                if (selected === 'SOME_PREDEFINED_VALUE' && items === 'SOME_OTHER_PREDEFINED_ITEM') {
                    // do this and that
                }
            }),
            map(([selected, items]) => {
                var targetItem = items.find(x => x.id === selected);
                return someProcess(targetItem.someProperyOfThisItem);
            })
        );

您还可以点击$itemsWithSelected observable 本身,如下所示:

    $itemsWithSelected
        .pipe(
            tap((value: TheTypeReturnedFromSomeProcessFunction) => {
                // check the emitted value here
                if (value === 'SOME_PREDEFINED_VALUE') {
                    // do this and that
                }
            })
        );

请注意,在map之后,stream 发出的值将是代码中不清楚的someProcess返回的类型(我将其标记为TheTypeReturnedFromSomeProcessFunction

这是我如何做到的->

it('should have correct items per selected',
    fakeAsync(() => {
      component.items$.subscribe(x => {
        expect(x.length).toBe(2); // some value
      });
      tick(200);
       
      component.onSelectItem({ value: { id: 1 } });

      tick(200);

      component.$itemsWithSelected.subscribe(items => {
        expect(items.length).toBe(2);
        expect(items[0].name).toBe("someName");
      });

      flush();
    }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM