4

I test a component with Spectator which contain in it's 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$)
        );
  }

The querySuggestion$ observable is binded through an async pipe. My problem is I try to do an integration test which can trigger my searchControl et look if the getSuggestion method is correctly called.

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

  }));

The code tap(value => console.log(value)) is never called and my test failed on the haveBeenCalled which return 0.

Angular version: 8.2.10
Jest: 24.9.0

skyboyer
  • 22,209
  • 7
  • 57
  • 64
zagoa
  • 798
  • 4
  • 23
  • have you tried using formcontrol.setValue instead of manipulating the native DOM element? my first guess here would be that the component is listening \for to the formcontrol value changes observable. and by setting the native DOM element, you are not triggering the value changes event. . i.e. `component.searchControl.setValue('test');`. using set Value should then trigger the value changes. – Edward Jan 21 '20 at 13:15
  • Yes I tried it spectator.component.searchControl.setValue('test'); spectator.tick(300); But I had no result :/ – zagoa Jan 21 '20 at 13:35
  • try adding `fixture.detectChanges()` between `setValue()` & `tick()` – Edward Jan 21 '20 at 14:02
  • Still not working. (FYI: tick trigger tick and a detectChanges) – zagoa Jan 21 '20 at 15:21
  • Currently hit a similar issue. I have an Observable based on valueChanges from a form that should display data. But it looks like valueChanges is never triggered. @zagoa did you find a solution? – DaSch Jan 11 '22 at 11:51

0 Answers0