4

I am trying to test if a button was clicked by the following way:

When the button is clicked some element class is changed from wrapper-container to wrapper-container-expanded(I don't want to check if the function is called when the button is clicked - this is not my purpose).

I am trying to check this in the following way:

it('should class be changed', ()=>{ 
   fixture.detectChanges()
   clickedElement.nativeElement.click() // click the button that causes the class change
   elementToBeExpanded = fixture.debugElement.nativeElement.querySelector('wrapper-container-expanded')
   expext(elementToBeExpanded).toBeTruthy() // check if the element with the new class exists in the DOM -the elementToBeExpanded is null
})

Although I can see that the function is called and the class is changed, the element with the new class cannot be found and the old wrapper-container appears to exist.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
MD10
  • 1,313
  • 3
  • 12
  • 35
  • For component states, and simple actions I recommend to have a look in the Angular Testing library. Its an awesome tool for this cases. https://github.com/testing-library/angular-testing-library – Ricardo Ferreira Dec 02 '19 at 12:41

1 Answers1

4

You need to call fixture.detectChanges() after the click event.

it('should class be changed', () => { 
   // ...
   clickedElement.nativeElement.click() // click the button that causes the class change
   fixture.detectChanges()              // detect the changes!!
   // ...
})
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • also when I add spyOn(component, 'the function that casuses the change class') the test breaks.. any clue ? – MD10 Dec 02 '19 at 12:56
  • 1
    I figured it out by myself the spyOn creates mock of that method and it was not called untill I added .and.callThrough().. – MD10 Dec 02 '19 at 13:29
  • 1
    Great you found it! Yes, indeed, if you install a spy on some method and want the real method to be called you need [`and.callThrough`](https://jasmine.github.io/2.0/introduction#section-Spies:_%3Ccode%3Eand.callThrough%3C/code%3E) – lealceldeiro Dec 02 '19 at 13:31