如何测试具有去抖动时间的效果?

NiZ*_*iZa 3 rxjs ngrx ngrx-effects angular

我正在使用 NgRx 并想测试我的效果。有些效果确实有去抖动时间。像这个例子:

@Effect() searchImage$ = this.actions$.pipe( ofType(fromImageLibraryActions.SEARCH_IMAGES), map((action: fromImageLibraryActions.SearchImages) => action.query), debounceTime(300), switchMap(query: string) => this.imageLibraryService.getImagesBySearching(query)), map((images: LibraryImage[]) => new fromImageLibraryActions.LoadImages(images)));

我如何正确测试它们。我尝试了以下方法:

describe('SearchImages$', () => {
   it('should return loadImages action', fakeAsync(() => {
        const action = new fromImageLibraryActions.SearchImages('test');
        const images = [
            { uploaderId: 1 } as LibraryImage,
            { uploaderId: 2 } as LibraryImage
        ];

        const loadImagesAction = new fromImageLibraryActions.LoadImages(images);

        actions$ = hot('--a-', { a: action });

        tick(300);
        getTestScheduler().flush();

        const expected = cold('--b-', { b: loadImagesAction });
        expect(effects.searchImage$).toBeObservable(expected);          
   }));
});
Run Code Online (Sandbox Code Playgroud)

tim*_*ver 5

ngrx 示例应用程序有一个示例,请参阅此处的代码:

it('should return a new book.SearchComplete, with the books, on success, after the de-bounce', () => {
  const book1 = { id: '111', volumeInfo: {} } as Book;
  const book2 = { id: '222', volumeInfo: {} } as Book;
  const books = [book1, book2];
  const action = new FindBookPageActions.SearchBooks('query');
  const completion = new BooksApiActions.SearchSuccess(books);

  actions$ = hot('-a---', { a: action });
  const response = cold('-a|', { a: books });
  const expected = cold('-----b', { b: completion });
  googleBooksService.searchBooks = jest.fn(() => response);

  expect(
    effects.search$({
      debounce: 30,
      scheduler: getTestScheduler(),
    })
  ).toBeObservable(expected);
});
Run Code Online (Sandbox Code Playgroud)

更多信息可以在ngrx/effects testing docs 中找到