4

What I'm trying to do is get the reference of a button in order to simulate a click event, my main problem is that the button is not rendering cause the component is not detecting the change of a list that should be populated by that time.

Here is my unit test code :

it('should add more cases when load more cases button is clicked', () => {
    spyOn(component, 'loadMoreCases');
    
    component.cases$.subscribe((cases) => {
      fixture.detectChanges();
      let buttons = fixture.debugElement.nativeElement.querySelectorAll('[nz-button]') as HTMLButtonElement[];
      buttons[1].click();

      expect(component.loadMoreCases).toBeCalled;
    });
    
    component.ngAfterViewInit();
    fixture.detectChanges();
  
  });

here is the *ngIf part in the HTML: enter image description here

here is the service that is called after view init in the main component:

 ngAfterViewInit(): void {
    this.caseService
      .getPaginatedCases(1, 15)
      .pipe(take(1))
      .subscribe((cases) => {
        this.cases$.next(cases.list);
        this.amountOfCases = cases.total;
      });
  }

I just want to know how to tell angular that the cases have some mock data already and inform the component to rerender in order to be able to access the button that it's in the *ngIf, I had been trying with everything, fakeAsync() using the tick function, async using done function, but nothing had worked.

Rémi Benoit
  • 1,307
  • 11
  • 17

1 Answers1

0

How are you providing the data? Mocking the service and then returning them should be enough for it to work:

const getPaginatedCases = spyOn(caseService, "getPaginatedCasees");

getPaginatedCases.and.returnValue(of(mockCases));

Of course, it's important that this is run before ngOnInit() (you have the initializer in ngAfterViewInit(), but I think it belongs in init – doesn't matter for the sake of this answer anyway) is called, so fixture.detectChanges() can only be called after this has run. Don't forget that you might have a fixture.detectChanges() in the beforeEach() that is messing you up.

Elias
  • 3,592
  • 2
  • 19
  • 42