unit test method async angular testing jasmine settimeout karma-jasmine

angular - test - Pruebe una función que contenga un setTimeout()



testing angular 2 (1)

Puedes hacer una de estas dos cosas:

1: en realidad espere en la prueba 250 + 1 ms en un setTimeout() , luego verifique si el elemento realmente desapareció.

2: use fakeAsync() y tick() para simular el tiempo en la prueba - un tick() resolverá el setTimeout en el close() original close() , y la verificación podría ocurrir inmediatamente después en un fixture.whenStable().then(...) .

Por ejemplo:

it("tests the exit button click", fakeAsync(() => { comp.close() tick(500) fixture.detectChanges() fixture.whenStable().then(() => { const popUpWindow = fixture.debugElement.query(By.css("#popup-window")) expect(popUpWindow).toBe(null) }) }))

Sugiero usar el segundo, ya que es mucho más rápido que esperar el método original. Si todavía usa el 1er, intente disminuir el tiempo de espera antes de la prueba para hacer que funcione más rápido.

Tengo una función cercana en mi componente que contiene un setTimeout() para dar tiempo a que termine la animación.

public close() { this.animate = "inactive" setTimeout(() => { this.show = false }, 250) }

this.show está vinculado a un ngIf .

this.animate está vinculado a una animación.

Tengo una prueba que necesita probar esta función

it("tests the exit button click", () => { comp.close() fixture.detectChanges() //verifies the element is no longer in the DOM const popUpWindow = fixture.debugElement.query(By.css("#popup-window")) expect(popUpWindow).toEqual(null) })

¿Cómo se prueba adecuadamente esta función cuando hay un setTimeout() ?

Estaba usando jasmine.clock().tick(251) pero la ventana nunca desaparecería. ¿Alguna idea sobre esto también?