如何单元测试rxjs debounceTime逻辑(Angular)?

时间:2017-07-21 12:59:54

标签: angular unit-testing typescript rxjs

由于我对RxJ缺乏了解,我复制 - >粘贴使用了一些代码,修改了它,现在无法测试它...

以下是整个组件:

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operator/map';
import { debounceTime } from 'rxjs/operator/debounceTime';
import { distinctUntilChanged } from 'rxjs/operator/distinctUntilChanged';
import { _catch } from 'rxjs/operator/catch';
import { _do } from 'rxjs/operator/do';
import { switchMap } from 'rxjs/operator/switchMap';
import { of } from 'rxjs/observable/of';

import { ApiService } from '../../services/api/api.service';

import { ISearchSuggestion } from './search.interface';

@Component({
  selector: 'msm-search',
  templateUrl: './search.component.html'
})
export class SearchComponent {
  public model: string;

  private _isSearching = false;
  get isSearching() { return this._isSearching; }

  constructor(
    private router: Router,
    private apiService: ApiService
  ) {}

  search = (text$: Observable<string>) => {
    return _do.call(
      switchMap.call(
        _do.call(
          distinctUntilChanged.call(
            debounceTime.call(text$, 300)),
            this.enableSearching.bind(this)
          ),
        this.performSearch.bind(this)
      ),
      () => {
        this._isSearching = false;
      }
    );
  }

  private enableSearching(term: string) {
    if (term.length > 2) {
      this._isSearching = true;
    }
  }

  private performSearch(term: string) {
    if (term.length > 2) {
      return _catch.call(
        _do.call(this.apiService.getSearchSuggestions(term)),
        () => of.call([])
      )
    }
  }
}

我想测试搜索但是既没有setTimeout,也没有jasmine.tick()似乎做了一个技巧,这里是我提出的例子:

it('Should get suggestions if search term is longer than 2 characters', (done) => {
  const searchTerm = '123test';
  const stringObservable = new Observable<string>(observer => {
    setTimeout(() => {
      observer.next(searchTerm);
      observer.complete();
    }, 50);
  });
  spyOn(apiService, 'getSearchSuggestions');
  component.search(stringObservable);
  setTimeout(() => {
    expect(apiService.getSearchSuggestions).toHaveBeenCalledWith(searchTerm);
    done();
  }, 500);
});

我做错了什么?

1 个答案:

答案 0 :(得分:0)

tick 应该是用来实现

的东西

component.search(stringObservable); tick(500); expect(apiService.getSearchSuggestions).toHaveBeenCallediith(searchTerm);

这不起作用?

相关问题