{ "id": "guide/testing-utility-apis", "title": "Testing Utility APIs", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Testing Utility APIslink

\n

This page describes the most useful Angular testing features.

\n

The Angular testing utilities include the TestBed, the ComponentFixture, and a handful of functions that control the test environment.\nThe TestBed and ComponentFixture classes are covered separately.

\n

Here's a summary of the stand-alone functions, in order of likely utility:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Function\n \n Description\n
\n waitForAsync\n \n

Runs the body of a test (it) or setup (beforeEach) function within a special async test zone.\nSee discussion above.

\n
\n fakeAsync\n \n

Runs the body of a test (it) within a special fakeAsync test zone, enabling\na linear control flow coding style. See discussion above.

\n
\n tick\n \n

Simulates the passage of time and the completion of pending asynchronous activities\nby flushing both timer and micro-task queues within the fakeAsync test zone.

\n
\n

The curious, dedicated reader might enjoy this lengthy blog post,\n\"Tasks, microtasks, queues and schedules\".

\n
\n

Accepts an optional argument that moves the virtual clock forward\nby the specified number of milliseconds,\nclearing asynchronous activities scheduled within that timeframe.\nSee discussion above.

\n
\n inject\n \n

Injects one or more services from the current TestBed injector into a test function.\nIt cannot inject a service provided by the component itself.\nSee discussion of the debugElement.injector.

\n
\n discardPeriodicTasks\n \n

When a fakeAsync() test ends with pending timer event tasks (queued setTimeOut and setInterval callbacks),\nthe test fails with a clear error message.

\n

In general, a test should end with no queued tasks.\nWhen pending timer tasks are expected, call discardPeriodicTasks to flush the task queue\nand avoid the error.

\n
\n flushMicrotasks\n \n

When a fakeAsync() test ends with pending micro-tasks such as unresolved promises,\nthe test fails with a clear error message.

\n

In general, a test should wait for micro-tasks to finish.\nWhen pending microtasks are expected, call flushMicrotasks to flush the micro-task queue\nand avoid the error.

\n
\n ComponentFixtureAutoDetect\n \n

A provider token for a service that turns on automatic change detection.

\n
\n getTestBed\n \n

Gets the current instance of the TestBed.\nUsually unnecessary because the static class methods of the TestBed class are typically sufficient.\nThe TestBed instance exposes a few rarely used members that are not available as\nstatic methods.

\n
\n\n

TestBed class summarylink

\n

The TestBed class is one of the principal Angular testing utilities.\nIts API is quite large and can be overwhelming until you've explored it,\na little at a time. Read the early part of this guide first\nto get the basics before trying to absorb the full API.

\n

The module definition passed to configureTestingModule\nis a subset of the @NgModule metadata properties.

\n\n type TestModuleMetadata = {\n providers?: any[];\n declarations?: any[];\n imports?: any[];\n schemas?: Array<SchemaMetadata | any[]>;\n };\n\n\n

Each override method takes a MetadataOverride<T> where T is the kind of metadata\nappropriate to the method, that is, the parameter of an @NgModule,\n@Component, @Directive, or @Pipe.

\n\n type MetadataOverride<T> = {\n add?: Partial<T>;\n remove?: Partial<T>;\n set?: Partial<T>;\n };\n\n\n\n

The TestBed API consists of static class methods that either update or reference a global instance of the TestBed.

\n

Internally, all static methods cover methods of the current runtime TestBed instance,\nwhich is also returned by the getTestBed() function.

\n

Call TestBed methods within a beforeEach() to ensure a fresh start before each individual test.

\n

Here are the most important static methods, in order of likely utility.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Methods\n \n Description\n
\n configureTestingModule\n \n

The testing shims (karma-test-shim, browser-test-shim)\nestablish the initial test environment and a default testing module.\nThe default testing module is configured with basic declaratives and some Angular service substitutes that every tester needs.

\n

Call configureTestingModule to refine the testing module configuration for a particular set of tests\nby adding and removing imports, declarations (of components, directives, and pipes), and providers.

\n
\n compileComponents\n \n

Compile the testing module asynchronously after you've finished configuring it.\nYou must call this method if any of the testing module components have a templateUrl\nor styleUrls because fetching component template and style files is necessarily asynchronous.\nSee above.

\n

After calling compileComponents, the TestBed configuration is frozen for the duration of the current spec.

\n
\n createComponent\n \n

Create an instance of a component of type T based on the current TestBed configuration.\nAfter calling compileComponent, the TestBed configuration is frozen for the duration of the current spec.

\n
\n overrideModule\n \n

Replace metadata for the given NgModule. Recall that modules can import other modules.\nThe overrideModule method can reach deeply into the current testing module to\nmodify one of these inner modules.

\n
\n overrideComponent\n \n

Replace metadata for the given component class, which could be nested deeply\nwithin an inner module.

\n
\n overrideDirective\n \n

Replace metadata for the given directive class, which could be nested deeply\nwithin an inner module.

\n
\n overridePipe\n \n

Replace metadata for the given pipe class, which could be nested deeply\nwithin an inner module.

\n
\n \n inject\n \n

Retrieve a service from the current TestBed injector.

\n

The inject function is often adequate for this purpose.\nBut inject throws an error if it can't provide the service.

\n

What if the service is optional?

\n

The TestBed.inject() method takes an optional second parameter,\nthe object to return if Angular can't find the provider\n(null in this example):

\n

\nservice = TestBed.inject(NotProvided, null); // service is null\n\n

\n

After calling TestBed.inject, the TestBed configuration is frozen for the duration of the current spec.

\n
\n \n initTestEnvironment\n \n

Initialize the testing environment for the entire test run.

\n

The testing shims (karma-test-shim, browser-test-shim) call it for you\nso there is rarely a reason for you to call it yourself.

\n

You may call this method exactly once. If you must change\nthis default in the middle of your test run, call resetTestEnvironment first.

\n

Specify the Angular compiler factory, a PlatformRef, and a default Angular testing module.\nAlternatives for non-browser platforms are available in the general form\n@angular/platform-<platform_name>/testing/<platform_name>.

\n
\n resetTestEnvironment\n \n

Reset the initial test environment, including the default testing module.

\n
\n

A few of the TestBed instance methods are not covered by static TestBed class methods.\nThese are rarely needed.

\n\n

The ComponentFixturelink

\n

The TestBed.createComponent<T>\ncreates an instance of the component T\nand returns a strongly typed ComponentFixture for that component.

\n

The ComponentFixture properties and methods provide access to the component,\nits DOM representation, and aspects of its Angular environment.

\n\n

ComponentFixture propertieslink

\n

Here are the most important properties for testers, in order of likely utility.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Properties\n \n Description\n
\n componentInstance\n \n

The instance of the component class created by TestBed.createComponent.

\n
\n debugElement\n \n

The DebugElement associated with the root element of the component.

\n

The debugElement provides insight into the component and its DOM element during test and debugging.\nIt's a critical property for testers. The most interesting members are covered below.

\n
\n nativeElement\n \n

The native DOM element at the root of the component.

\n
\n changeDetectorRef\n \n

The ChangeDetectorRef for the component.

\n

The ChangeDetectorRef is most valuable when testing a\ncomponent that has the ChangeDetectionStrategy.OnPush method\nor the component's change detection is under your programmatic control.

\n
\n\n

ComponentFixture methodslink

\n

The fixture methods cause Angular to perform certain tasks on the component tree.\nCall these method to trigger Angular behavior in response to simulated user action.

\n

Here are the most useful methods for testers.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Methods\n \n Description\n
\n detectChanges\n \n

Trigger a change detection cycle for the component.

\n

Call it to initialize the component (it calls ngOnInit) and after your\ntest code, change the component's data bound property values.\nAngular can't see that you've changed personComponent.name and won't update the name\nbinding until you call detectChanges.

\n

Runs checkNoChanges afterwards to confirm that there are no circular updates unless\ncalled as detectChanges(false);

\n
\n autoDetectChanges\n \n

Set this to true when you want the fixture to detect changes automatically.

\n

When autodetect is true, the test fixture calls detectChanges immediately\nafter creating the component. Then it listens for pertinent zone events\nand calls detectChanges accordingly.\nWhen your test code modifies component property values directly,\nyou probably still have to call fixture.detectChanges to trigger data binding updates.

\n

The default is false. Testers who prefer fine control over test behavior\ntend to keep it false.

\n
\n checkNoChanges\n \n

Do a change detection run to make sure there are no pending changes.\nThrows an exceptions if there are.

\n
\n isStable\n \n

If the fixture is currently stable, returns true.\nIf there are async tasks that have not completed, returns false.

\n
\n whenStable\n \n

Returns a promise that resolves when the fixture is stable.

\n

To resume testing after completion of asynchronous activity or\nasynchronous change detection, hook that promise.\nSee above.

\n
\n destroy\n \n

Trigger component destruction.

\n
\n\n

DebugElementlink

\n

The DebugElement provides crucial insights into the component's DOM representation.

\n

From the test root component's DebugElement returned by fixture.debugElement,\nyou can walk (and query) the fixture's entire element and component subtrees.

\n

Here are the most useful DebugElement members for testers, in approximate order of utility:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Member\n \n Description\n
\n nativeElement\n \n

The corresponding DOM element in the browser (null for WebWorkers).

\n
\n query\n \n

Calling query(predicate: Predicate<DebugElement>) returns the first DebugElement\nthat matches the predicate at any depth in the subtree.

\n
\n queryAll\n \n

Calling queryAll(predicate: Predicate<DebugElement>) returns all DebugElements\nthat matches the predicate at any depth in subtree.

\n
\n injector\n \n

The host dependency injector.\nFor example, the root element's component instance injector.

\n
\n componentInstance\n \n

The element's own component instance, if it has one.

\n
\n context\n \n

An object that provides parent context for this element.\nOften an ancestor component instance that governs this element.

\n

When an element is repeated within *ngFor, the context is an NgForRow whose $implicit\nproperty is the value of the row instance value.\nFor example, the hero in *ngFor=\"let hero of heroes\".

\n
\n children\n \n

The immediate DebugElement children. Walk the tree by descending through children.

\n
\n

DebugElement also has childNodes, a list of DebugNode objects.\nDebugElement derives from DebugNode objects and there are often\nmore nodes than elements. Testers can usually ignore plain nodes.

\n
\n
\n parent\n \n

The DebugElement parent. Null if this is the root element.

\n
\n name\n \n

The element tag name, if it is an element.

\n
\n triggerEventHandler\n \n

Triggers the event by its name if there is a corresponding listener\nin the element's listeners collection.\nThe second parameter is the event object expected by the handler.\nSee above.

\n

If the event lacks a listener or there's some other problem,\nconsider calling nativeElement.dispatchEvent(eventObject).

\n
\n listeners\n \n

The callbacks attached to the component's @Output properties and/or the element's event properties.

\n
\n providerTokens\n \n

This component's injector lookup tokens.\nIncludes the component itself plus the tokens that the component lists in its providers metadata.

\n
\n source\n \n

Where to find this element in the source component template.

\n
\n references\n \n

Dictionary of objects associated with template local variables (e.g. #foo),\nkeyed by the local variable name.

\n
\n\n

The DebugElement.query(predicate) and DebugElement.queryAll(predicate) methods take a\npredicate that filters the source element's subtree for matching DebugElement.

\n

The predicate is any method that takes a DebugElement and returns a truthy value.\nThe following example finds all DebugElements with a reference to a template local variable named \"content\":

\n\n// Filter for DebugElements with a #content reference\nconst contentRefs = el.queryAll( de => de.references.content);\n\n\n

The Angular By class has three static methods for common predicates:

\n\n\n// Can find DebugElement either by css selector or by directive\nconst h2 = fixture.debugElement.query(By.css('h2'));\nconst directive = fixture.debugElement.query(By.directive(HighlightDirective));\n\n\n\n \n
\n\n\n" }