puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

async in Angular Testing #39

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

The async in Angular Testing is complicated than regular conception.

It has two conceptions.

As a Function

It Wraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done.

The TestBed.compileComponents() method calls XHR to read external template and css files during "just-in-time" compilation. Write tests that call compileComponents() with the async() utility.

it('...', async( (object) => {
  object.doSomething.then(() => {
    expect(...);
  })
});

The async( ) utility hides some asynchronous boilerplate by arranging for the tester's code to run in a special async test zone. You DON'T need to pass Jasmine's done( ) into the test and call done( ) because it is undefined in promise or observable callbacks.

when it is used , it needs to be imported as following

import { async  } from '@angular/core/testing';

In the test, cause XHR calls within a test are rare so normally fakeAsync would be enough.

Normally only be used for the beforeEach

As an Async Function Expression

This concept is taken from JavaScript directly.

Therefore it displays as following, notice the differens with ( ) and done, and it DOES NOT need to be imported.

And it is used quite often.

it('...', async( done ) => {
  fixture.whenStable().then(() => {
    expect(...);
    done( );
  })
});

normally for both cases we need to use fixture.whenStable().then(() => { under this setting. The fixture.whenStable() returns a promise that resolves when the JavaScript engine's task queue becomes empty.

Conclusion

-- as Function as Expression
done no yes
imported yes no
whenStable yes yes
usage seldom often