When do you use the async function in the TestBed when testing in Angular 2?
When do you use this?
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
});
And when do you use this?
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
}));
Can anyone enlighten me on this ?
When you make an async call in your test the actual test function is completed before the async call is completed. When you need to verify some state when the call was completed (which is usually the case) then the test framework would report the test as completed while there is still async work going on.
With using
async(...)
you tell the test framework to wait until the return promise or observable is completed before treating the test as completed.The code passed to
then(...)
will be executed after the test function itself completed. Withasync()
you make the test framework aware, that it needs to wait for promises and observables to complete before treating the test as completed.See also
async
will not allow the next test to start until theasync
finishes all its tasks. Whatasync
does is wrap the callback in a Zone, where all asynchronous tasks (e.g.setTimeout
) are tracked. Once all the asynchronous tasks are complete, then theasync
completes.If you have ever worked with Jasmine outside out Angular, you may have seen
done
being passed to the callbackHere, this is native Jasmine, where we tell Jasmine that this test should delay completion until we call
done()
. If we didn't calldone()
and instead did this:The test would complete even before the expectation, because the promise resolves after the test is finished executing the synchronous tasks.
With Angular (in a Jasmine environment), Angular will actually call
done
behind the scenes when we useasync
. It will keep track of all the asynchronous tasks in the Zone, and when they are all finished,done
will be called behind the scenes.In your particular case with the
TestBed
configuration, you would use this generally when you want tocompileComponents
. I rarely run into a situation in which I would have to call it otherwiseWhen testing a component that uses
templateUrl
(if you are not using webpack), then Angular needs to make an XHR request to get the template, so the compilation of the component would be asynchronous. So we should wait until it resolves before continuing testing.