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

时间:2018-10-30 08:32:25

标签: angular rxjs ngrx ngrx-effects

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

i_rownum i_level segment parent   1   0   A1   -   2   1   B1   A1   3   2   C1   B1   4   1   B2   A1   5   2   C2   B2   6   1   B3   A1   7   2   C3   B3   8   3   D1   C3   9   3   D2   C3   10   1   B4   A1

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

@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)));

2 个答案:

答案 0 :(得分:3)

ngrx example-app有一个示例,请参见代码here

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);
});

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

答案 1 :(得分:0)

ngrx示例不适用于我,因此我创建了this article,它说明了如何使用debounceTime测试ngrx效果。

特定测试在GitHub here上进行,如下所示:

import { TestBed } from '@angular/core/testing';
import { provideMockActions } from '@ngrx/effects/testing';
import { cold, getTestScheduler, hot } from 'jasmine-marbles';
import { Observable } from 'rxjs';
import { loadClients, networkRequest } from './client.actions';

import { ClientEffects } from './client.effects';

describe('ClientEffects', () => {
  let actions$: Observable<any>;
  let effects: ClientEffects;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        ClientEffects,
        provideMockActions(() => actions$)
      ]
    });

    effects = TestBed.inject<ClientEffects>(ClientEffects);
  });

  it('dispatch networkRequest', () => {
    const scheduler = getTestScheduler();
    scheduler.run(() => {
      // marbles
      const actions =  'a 500ms a b';
      const expected = '500ms a - 500ms b';

      actions$ = hot(actions, {
        a: loadClients(),
        b: loadClients(),
      });

      expect(effects.loadClients$).toBeObservable(cold(expected, {
        a: networkRequest(),
        b: networkRequest(),
      }));
    });
  });
});