Angular 7 测试 - 用去抖动时间模拟输入事件

Mar*_*oLe 5 rxjs angular angular-test

在开始这个问题之前。我知道,有很多类似的问题和我的一样。但没有任何解决方案能够帮助我。

我用 rxjs 创建了一个自定义的自动完成,并想测试一个方法是否在输入事件上被调用。但错误表明该方法从未被调用,例如:

 Expected spy CityService.getLocation to have been called with [ 'mun' ] but it was never called.
Run Code Online (Sandbox Code Playgroud)

html

我通过async管道在 HTML 中订阅了我的 observable 。

 Expected spy CityService.getLocation to have been called with [ 'mun' ] but it was never called.
Run Code Online (Sandbox Code Playgroud)

成分

      <input type="text" [(ngModel)]="location" class="form-control" id="locationSearchInput"/>
      <div class="spacer">
        <p class="invalid-feedBack" *ngIf="searchFailed && location.length > 0">Nothing found.</p>
        <ul id="search" *ngFor="let item of (search | async)">
          <li class="resultItem" type="radio" (click)="location = item">{{item}}</li>
      </ul>
    </div>
Run Code Online (Sandbox Code Playgroud)

测试

      ngOnInit(): void {
        this.search = fromEvent(document.getElementById('locationSearchInput'), 'input').pipe(
          debounceTime(750),
          distinctUntilChanged(),
          map((eventObj: Event) => (<HTMLInputElement>eventObj.target).value),
          switchMap((term: string) => this.cityService.getLocation(term)) <== should get called
        );
      }
Run Code Online (Sandbox Code Playgroud)

我也尝试使用fakeAsyncwith tick(750)。但没有任何帮助。在console.log该测试中还示出了一个空字符串作为输入值。所以也许我正在模拟错误的事件。

Mar*_*oLe 4

我的测试使用以下配置:

\n\n
  it('should search for location on init', fakeAsync(() => {\n    const spy = (<jasmine.Spy>cityServiceStub.getLocation).and.returnValue(of(['Munich', 'M\xc3\xbcnster']));\n\n    fixture.detectChanges();\n\n    const rendered: DebugElement = fixture.debugElement.query(By.css('#locationSearchInput'));\n\n    rendered.nativeElement.value = 'mun';\n    rendered.nativeElement.dispatchEvent(new Event('input'));\n\n    tick(750);\n    fixture.detectChanges();\n\n    expect(spy).toHaveBeenCalledWith('mun');\n  }));\n
Run Code Online (Sandbox Code Playgroud)\n\n

['Munich', 'M\xc3\xbcnster']我错过了作为一个 Observable 与操作员一起返回of()。我应该习惯tick(750)等待事件更改的特定去抖时间。

\n