Search code examples
angularangular9angular-test

Angular testing with interval()


In my ngOnInit I check a route, do some stuff, and then setup an interval

ngOnInit(): void {
    this.routeSubscription = this.route.paramMap.subscribe(x => {
         ...
         // Reload the data every 60 seconds
         interval(60_000)
             .pipe(takeUntil(this.cancelInterval$))
             .subscribe(() => this.rows$ = this.orderService.active())
    })
}

When I try to do my unit testing, jasmine aborts because the async method didn't return fast enough. I'm doing this (as a sub-describe of the main one, which does all the normal TestBed setups):

describe('when showing active orders', () => {
    beforeEach(() => {
        activatedRoute.setParamMap({})
        fixture.detectChanges()
    })

    it('...', async () => {
        await fixture.whenStable()
        ...
    })

It seems to be stuck because of the interval. I thought I could just put a call to discardPeriodicTasks() at the end of the beforeEach method, but that doesn't work.

So I'm looking for either the right way to handle this in testing, or a way in the production code to only make the interval call if it's not being run via testing.

Angular CLI: 9.0.7
Node: 14.4.0
Angular: 9.1.6


Solution

  • You can use fakeAsync and tick to simulate the async behaviour

    it('...', fakeAsync () => { tick(60000); doTestStuff(); })