Angular 6,Rxjs,Jest,茉莉花大理石。
非常常见的情况:搜索服务器端项目的组件。在该组件中,有一些控件可以更改搜索条件,我想以“反应式”的方式进行编码。所以在组件代码中,我有这样的东西:
class SearchComponent implements OnInit {
public searchData: SearchData = {};
public searchConditions$ = new Subject<SearchData>();
constructor(private searchService: SearchService) { }
public results$: Observable<ResultData> = this.searchConditions$.pipe(
distinctUntilChanged(this.compareProperties), // omissis but it works
flatMap(searchData => this.searchService.search(searchData)),
shareReplay(1)
);
// search actions
ngOnInit() {
this.searchConditions$.next(this.searchData);
}
public onChangeProp1(prop1: string) {
this.searchData = { ...this.searchData, prop1 };
this.searchConditions$.next(this.searchData);
}
public onChangeProp2(prop2: string) {
this.searchData = { ...this.searchData, prop2 };
this.searchConditions$.next(this.searchData);
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,Subject每当用户界面中的某些内容发生更改时,它就会触发搜索条件。
现在,我想测试搜索服务将仅针对不同的输入被调用。我可以用这种方式“不用弹珠”来做:
test('when searchConditions$ come with equal …Run Code Online (Sandbox Code Playgroud)