Tengo dificultades para hacer que mi prueba unitaria funcione junto con un Observable con operador de retraso. La aplicación se basa en Angular 2 y las pruebas se ejecutan en karma/jasmine. Probé los métodos auxiliares async y fakeAsync, pero ninguno funciona.
Aquí hay un bloque de código simplificado (sin Angular 2) que explica mi problema.
let mouseDownStream = Rx.Observable.fromEvent(document.body, 'mousedown'); let haveBeenCalled = false; mouseDownStream.delay(200).subscribe(() => haveBeenCalled = true); describe('mouse down event', () => { it('it should emit an event stream after 200ms', (done) => { document.body.dispatchEvent(new MouseEvent('mousedown')) expect(haveBeenCalled).toBeFalsy(); // Don't want this setTimeout should use Angular's tick(200) method instead but it's not working. setTimeout(() => { expect(haveBeenCalled).toBeTruthy(); done(); }, 200) }); });Aquí hay un ejemplo de cómo probar un Observable con un operador de retraso en Angular 2+, si alguien todavía está buscando la respuesta:
import { fakeAsync, tick } from "@angular/core/testing"; import { fromEvent } from "rxjs"; import { delay } from "rxjs/operators"; describe("mouse down event", () => { it("should emit an event stream after 200ms", fakeAsync(() => { let mouseDownStream = fromEvent(document.body, "mousedown"); let haveBeenCalled = false; const subscription = mouseDownStream.pipe(delay(200)).subscribe(() => (haveBeenCalled = true)); document.body.dispatchEvent(new MouseEvent("mousedown")); expect(haveBeenCalled).toBeFalsy(); tick(200); expect(haveBeenCalled).toBeTruthy(); subscription.unsubscribe(); })); });Usando rxjs 6 con angular 12, fakeAsync no funciona para mí. Solo usando TestScheduler lo hizo. Modificando la muestra de Ritchie:
describe("mouse down event", () => { let testScheduler: TestScheduler; beforeEach(() => { testScheduler = new TestScheduler((act, exp) => expect(exp).toEqual(act) as any); }); fit("should emit an event stream after 200ms", () => { let mouseDownStream = fromEvent(document.body, "mousedown"); let haveBeenCalled = false; testScheduler.run(() => { const subscription = mouseDownStream.pipe(delay(200)).subscribe(() => (haveBeenCalled = true)); document.body.dispatchEvent(new MouseEvent("mousedown")); expect(haveBeenCalled).toBeFalsy(); testScheduler.createTime('200|'); testScheduler.flush(); expect(haveBeenCalled).toBeTruthy(); subscription.unsubscribe(); }); }); });