4

我用 Spectator 测试一个组件,其中包含 ngInit

  listenToSuggestions() {
    this.querySuggestions$ =
      this.searchControl.valueChanges
        .pipe(
          tap(value => console.log(value)),
          filter(value => value && value.length > 1),
          debounceTime(300),
          switchMap(searchInput => {
            return this.getSuggestion(searchInput);
          }),
          takeUntil(this.destroy$)
        );
  }

querySuggestion$ observable 通过异步管道绑定。我的问题是我尝试做一个集成测试,如果 getSuggestion 方法被正确调用,它可以触发我的 searchControl 和查看。

it('should trigger suggestions', fakeAsync(async () => {
    spectator.component.ngOnInit();

    spectator.detectChanges();
    await spectator.fixture.whenStable();
    spectator.detectChanges();

    const spyGetSuggestion = spyOn(spectator.component, 'getSuggestion');

    const input = spectator.query('input') as HTMLInputElement;
    expect(input.placeholder).toEqual('Search');

    // three different approach to trigger my formControl
    input.focus();
    input.value = 'test';
    input.dispatchEvent(new Event('input'));
    spectator.tick(300);

    spectator.typeInElement('test', input);
    spectator.tick(300);

    spectator.component.searchControl.setValue('test');
    spectator.tick(300);


    expect(spyGetSuggestion).toHaveBeenCalled();

  }));

该代码tap(value => console.log(value))从未被调用,我的测试在返回 0 的 haveBeenCalled 上失败。

角度版本
:8.2.10 笑话:24.9.0

4

0 回答 0