Intro to Angular Component testing
If we need to test a component we should know what can test every declaration in the component for that we should use a declaration statement in the beforeEach()
However, we will need something different here.
TestBed & Component Fixtures
TestBed
is the main utility available for Angular-specific testing. You’ll use TestBed.configureTestingModule
in your test suite’s beforeEach
block and give it an object with similar values as a regular NgModule for declarations, providers, and imports. You can then chain a call to compileComponents
to tell Angular to compile the declared components.
You can create a component fixture with TestBed.createComponent
. Fixtures have access to a debugElement
, which will give you access to the internals of the component fixture.
Change detection isn’t done automatically, so you’ll call detectChanges
on a fixture to tell Angular to run change detection.
Async
Wrapping the callback function of a test or the first argument of beforeEach
with async allows Angular to perform asynchronous compilation and wait until the content inside of the async block to be ready before continuing.
The async utility tells Angular to run the code in a dedicated test zone that intercepts promises. We briefly covered the async utility in our intro to unit testing in Angular when using compileComponents
, so let’s go over one more detail here; namely the use of async with whenStable
. whenStable allows us to wait until all promises have been resolved to run our expectations.
Last updated