Why doesn't async angular unit-test find DOM element? Why doesn't async angular unit-test find DOM element? angular angular

Why doesn't async angular unit-test find DOM element?


Unfortunately this seems to have something to do with the fakeAsync zone in particular and not asynchronous tests in particular.

I've managed to get a working asynchronous test to work with async instead of fakeAsync:

it('should asynchronously find absences in calendar view', async(() => {        fixture.detectChanges();        fixture.whenStable().then(() => {            console.log('asynchronous test');            printAbsenceReasons(fixture);            expect(getAbsenceElements(fixture).length).toEqual(35);        });    });}));

I've debugged both the failing fakeAsync and the successful synchronous tests. They both call a method called getMonthView in a library "calendar-utils" by the same author as "angular-calendar":https://github.com/mattlewis92/calendar-utils/blob/master/src/calendar-utils.ts

In this method both the Date parameters and also the other Date computations itself seem to go very wrong.

I can only assume currently that it's related to this known issue in zone.js. I'm on Angular 5.2, but I assume its still related. In any case I'm sure that my test code is essentially correct, but the problem lies elsewhere.


I'm pretty sure that the reason this is not working is because of how you have defined your spy. It is defined outside of a beforeEach block.

The way you have it now, your spy is created once, when the fixture starts up. And jasmine works by removing all old spies at the end of every test. So, by the second test, your spy no longer exists.

I would bet that if you switched your test order, then you would see the async test working, but the sync one not.

To fix, simply move this into a beforeEach block:

const absenceService = jasmine.createSpyObj('AbsenceService', ['findAbsences']);absenceService.findAbsences.and.returnValue(of([{}]));