This page describes the most useful Angular testing features.
The Angular testing utilities include the TestBed
, the ComponentFixture
, and a handful of functions that control the test environment. The TestBed and ComponentFixture classes are covered separately.
Here's a summary of the stand-alone functions, in order of likely utility:
Function | Description |
---|---|
waitForAsync | Runs the body of a test ( |
fakeAsync | Runs the body of a test ( |
tick | Simulates the passage of time and the completion of pending asynchronous activities by flushing both timer and micro-task queues within the fakeAsync test zone.
Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe. See discussion above. |
inject | Injects one or more services from the current |
discardPeriodicTasks | When a In general, a test should end with no queued tasks. When pending timer tasks are expected, call |
flushMicrotasks | When a In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call |
ComponentFixtureAutoDetect | A provider token for a service that turns on automatic change detection. |
getTestBed | Gets the current instance of the |
TestBed
class summaryThe TestBed
class is one of the principal Angular testing utilities. Its API is quite large and can be overwhelming until you've explored it, a little at a time. Read the early part of this guide first to get the basics before trying to absorb the full API.
The module definition passed to configureTestingModule
is a subset of the @NgModule
metadata properties.
type TestModuleMetadata = { providers?: any[]; declarations?: any[]; imports?: any[]; schemas?: Array<SchemaMetadata | any[]>; };
Each override method takes a MetadataOverride<T>
where T
is the kind of metadata appropriate to the method, that is, the parameter of an @NgModule
, @Component
, @Directive
, or @Pipe
.
type MetadataOverride<T> = { add?: Partial<T>; remove?: Partial<T>; set?: Partial<T>; };
The TestBed
API consists of static class methods that either update or reference a global instance of the TestBed
.
Internally, all static methods cover methods of the current runtime TestBed
instance, which is also returned by the getTestBed()
function.
Call TestBed
methods within a beforeEach()
to ensure a fresh start before each individual test.
Here are the most important static methods, in order of likely utility.
Methods | Description |
---|---|
configureTestingModule | The testing shims ( Call |
compileComponents | Compile the testing module asynchronously after you've finished configuring it. You must call this method if any of the testing module components have a After calling |
createComponent | Create an instance of a component of type |
overrideModule | Replace metadata for the given |
overrideComponent | Replace metadata for the given component class, which could be nested deeply within an inner module. |
overrideDirective | Replace metadata for the given directive class, which could be nested deeply within an inner module. |
overridePipe | Replace metadata for the given pipe class, which could be nested deeply within an inner module. |
inject | Retrieve a service from the current The What if the service is optional? The service = TestBed.inject(NotProvided, null); // service is null After calling |
initTestEnvironment | Initialize the testing environment for the entire test run. The testing shims ( You may call this method exactly once. If you must change this default in the middle of your test run, call Specify the Angular compiler factory, a |
resetTestEnvironment | Reset the initial test environment, including the default testing module. |
A few of the TestBed
instance methods are not covered by static TestBed
class methods. These are rarely needed.
ComponentFixture
The TestBed.createComponent<T>
creates an instance of the component T
and returns a strongly typed ComponentFixture
for that component.
The ComponentFixture
properties and methods provide access to the component, its DOM representation, and aspects of its Angular environment.
ComponentFixture
propertiesHere are the most important properties for testers, in order of likely utility.
Properties | Description |
---|---|
componentInstance | The instance of the component class created by |
debugElement | The The |
nativeElement | The native DOM element at the root of the component. |
changeDetectorRef | The The |
ComponentFixture
methodsThe fixture methods cause Angular to perform certain tasks on the component tree. Call these method to trigger Angular behavior in response to simulated user action.
Here are the most useful methods for testers.
Methods | Description |
---|---|
detectChanges | Trigger a change detection cycle for the component. Call it to initialize the component (it calls Runs |
autoDetectChanges | Set this to When autodetect is The default is |
checkNoChanges | Do a change detection run to make sure there are no pending changes. Throws an exceptions if there are. |
isStable | If the fixture is currently stable, returns |
whenStable | Returns a promise that resolves when the fixture is stable. To resume testing after completion of asynchronous activity or asynchronous change detection, hook that promise. See above. |
destroy | Trigger component destruction. |
The DebugElement
provides crucial insights into the component's DOM representation.
From the test root component's DebugElement
returned by fixture.debugElement
, you can walk (and query) the fixture's entire element and component subtrees.
Here are the most useful DebugElement
members for testers, in approximate order of utility:
Member | Description |
---|---|
nativeElement | The corresponding DOM element in the browser (null for WebWorkers). |
query | Calling |
queryAll | Calling |
injector | The host dependency injector. For example, the root element's component instance injector. |
componentInstance | The element's own component instance, if it has one. |
context | An object that provides parent context for this element. Often an ancestor component instance that governs this element. When an element is repeated within |
children | The immediate
|
parent | The |
name | The element tag name, if it is an element. |
triggerEventHandler | Triggers the event by its name if there is a corresponding listener in the element's If the event lacks a listener or there's some other problem, consider calling |
listeners | The callbacks attached to the component's |
providerTokens | This component's injector lookup tokens. Includes the component itself plus the tokens that the component lists in its |
source | Where to find this element in the source component template. |
references | Dictionary of objects associated with template local variables (e.g. |
The DebugElement.query(predicate)
and DebugElement.queryAll(predicate)
methods take a predicate that filters the source element's subtree for matching DebugElement
.
The predicate is any method that takes a DebugElement
and returns a truthy value. The following example finds all DebugElements
with a reference to a template local variable named "content":
// Filter for DebugElements with a #content reference const contentRefs = el.queryAll( de => de.references.content);
The Angular By
class has three static methods for common predicates:
By.all
- return all elements.By.css(selector)
- return elements with matching CSS selectors.By.directive(directive)
- return elements that Angular matched to an instance of the directive class.// Can find DebugElement either by css selector or by directive const h2 = fixture.debugElement.query(By.css('h2')); const directive = fixture.debugElement.query(By.directive(HighlightDirective));
© 2010–2021 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v11.angular.io/guide/testing-utility-apis