[英]How to do a simple angular Jasmine Unit testing when using RXJS reactive approach using a subject and a stream that calls a service
How can I do a simple angular Jasmine Unit testing when using RXJS reactive approach使用 RXJS 反应式方法时,如何进行简单的 angular Jasmine 单元测试
Here is my simple implementation of the component.这是我对该组件的简单实现。 I have an items stream that gets some collection of items.
我有一个项目 stream 可以收集一些项目。 Then I have a dropdown in HTML that calls the onSelectItem method which triggers the next() method of the selectedItemSubject.
然后我在 HTML 中有一个下拉菜单调用 onSelectItem 方法,该方法触发 selectedItemSubject 的 next() 方法。 My goal is to test the $itemsWithSelected stream - to check if it returns the correct value - which is influenced by the selected Item and the items stream.
我的目标是测试 $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);
}
To check a value, emitted by $itemsWithSelected
, you can chain a pipe and tap the emitted 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);
})
);
You can also put a tap on the $itemsWithSelected
observable itself, like so:您还可以点击
$itemsWithSelected
observable 本身,如下所示:
$itemsWithSelected
.pipe(
tap((value: TheTypeReturnedFromSomeProcessFunction) => {
// check the emitted value here
if (value === 'SOME_PREDEFINED_VALUE') {
// do this and that
}
})
);
note that after map
, the values emitted by the stream would be of the type returned by the someProcess
which is unclear from the code (I marked it as TheTypeReturnedFromSomeProcessFunction
)请注意,在
map
之后,stream 发出的值将是代码中不清楚的someProcess
返回的类型(我将其标记为TheTypeReturnedFromSomeProcessFunction
)
Here is how I did this ->这是我如何做到的->
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.