{ "id": "guide/testing-components-basics", "title": "Basics of testing components", "contents": "\n\n\n
A component, unlike all other parts of an Angular application,\ncombines an HTML template and a TypeScript class.\nThe component truly is the template and the class working together. To adequately test a component, you should test that they work together\nas intended.
\nSuch tests require creating the component's host element in the browser DOM,\nas Angular does, and investigating the component class's interaction with\nthe DOM as described by its template.
\nThe Angular TestBed
facilitates this kind of testing as you'll see in the sections below.\nBut in many cases, testing the component class alone, without DOM involvement,\ncan validate much of the component's behavior in an easier, more obvious way.
For the sample app that the testing guides describe, see the
For the tests features in the testing guides, see
Test a component class on its own as you would test a service class.
\nComponent class testing should be kept very clean and simple.\nIt should test only a single unit.\nAt first glance, you should be able to understand\nwhat the test is testing.
\nConsider this LightswitchComponent
which toggles a light on and off\n(represented by an on-screen message) when the user clicks the button.
You might decide only to test that the clicked()
method\ntoggles the light's on/off state and sets the message appropriately.
This component class has no dependencies. To test these types of classes, follow the same steps as you would for a service that has no dependencies:
\nHere is the DashboardHeroComponent
from the Tour of Heroes tutorial.
It appears within the template of a parent component,\nwhich binds a hero to the @Input
property and\nlistens for an event raised through the selected @Output
property.
You can test that the class code works without creating the DashboardHeroComponent
\nor its parent component.
When a component has dependencies, you may wish to use the TestBed
to both\ncreate the component and its dependencies.
The following WelcomeComponent
depends on the UserService
to know the name of the user to greet.
You might start by creating a mock of the UserService
that meets the minimum needs of this component.
Then provide and inject both the component and the service in the TestBed
configuration.
Then exercise the component class, remembering to call the lifecycle hook methods as Angular does when running the app.
\nTesting the component class is as easy as testing a service.
\nBut a component is more than just its class.\nA component interacts with the DOM and with other components.\nThe class-only tests can tell you about class behavior.\nThey cannot tell you if the component is going to render properly,\nrespond to user input and gestures, or integrate with its parent and child components.
\nNone of the class-only tests above can answer key questions about how the\ncomponents actually behave on screen.
\nLightswitch.clicked()
bound to anything such that the user can invoke it?Lightswitch.message
displayed?DashboardHeroComponent
?WelcomeComponent
?These may not be troubling questions for the simple components illustrated above.\nBut many components have complex interactions with the DOM elements\ndescribed in their templates, causing HTML to appear and disappear as\nthe component state changes.
\nTo answer these kinds of questions, you have to create the DOM elements associated\nwith the components, you must examine the DOM to confirm that component state\ndisplays properly at the appropriate times, and you must simulate user interaction\nwith the screen to determine whether those interactions cause the component to\nbehave as expected.
\nTo write these kinds of test, you'll use additional features of the TestBed
\nas well as other testing helpers.
The CLI creates an initial test file for you by default when you ask it to\ngenerate a new component.
\nFor example, the following CLI command generates a BannerComponent
in the app/banner
folder (with inline template and styles):
It also generates an initial test file for the component, banner-external.component.spec.ts
, that looks like this:
Because compileComponents
is asynchronous, it uses\nthe waitForAsync
utility\nfunction imported from @angular/core/testing
.
Please refer to the waitForAsync section for more details.
\nOnly the last three lines of this file actually test the component\nand all they do is assert that Angular can create the component.
\nThe rest of the file is boilerplate setup code anticipating more advanced tests that might become necessary if the component evolves into something substantial.
\nYou'll learn about these advanced test features below.\nFor now, you can radically reduce this test file to a more manageable size:
\nIn this example, the metadata object passed to TestBed.configureTestingModule
\nsimply declares BannerComponent
, the component to test.
There's no need to declare or import anything else.\nThe default test module is pre-configured with\nsomething like the BrowserModule
from @angular/platform-browser
.
Later you'll call TestBed.configureTestingModule()
with\nimports, providers, and more declarations to suit your testing needs.\nOptional override
methods can further fine-tune aspects of the configuration.
After configuring TestBed
, you call its createComponent()
method.
TestBed.createComponent()
creates an instance of the BannerComponent
,\nadds a corresponding element to the test-runner DOM,\nand returns a ComponentFixture
.
Do not re-configure TestBed
after calling createComponent
.
The createComponent
method freezes the current TestBed
definition,\nclosing it to further configuration.
You cannot call any more TestBed
configuration methods, not configureTestingModule()
,\nnor get()
, nor any of the override...
methods.\nIf you try, TestBed
throws an error.
The ComponentFixture is a test harness for interacting with the created component and its corresponding element.
\nAccess the component instance through the fixture and confirm it exists with a Jasmine expectation:
\nYou will add more tests as this component evolves.\nRather than duplicate the TestBed
configuration for each test,\nyou refactor to pull the setup into a Jasmine beforeEach()
and some supporting variables:
Now add a test that gets the component's element from fixture.nativeElement
and\nlooks for the expected text.
The value of ComponentFixture.nativeElement
has the any
type.\nLater you'll encounter the DebugElement.nativeElement
and it too has the any
type.
Angular can't know at compile time what kind of HTML element the nativeElement
is or\nif it even is an HTML element.\nThe app might be running on a non-browser platform, such as the server or a\nWeb Worker,\nwhere the element may have a diminished API or not exist at all.
The tests in this guide are designed to run in a browser so a\nnativeElement
value will always be an HTMLElement
or\none of its derived classes.
Knowing that it is an HTMLElement
of some sort, you can use\nthe standard HTML querySelector
to dive deeper into the element tree.
Here's another test that calls HTMLElement.querySelector
to get the paragraph element and look for the banner text:
The Angular fixture provides the component's element directly through the fixture.nativeElement
.
This is actually a convenience method, implemented as fixture.debugElement.nativeElement
.
There's a good reason for this circuitous path to the element.
\nThe properties of the nativeElement
depend upon the runtime environment.\nYou could be running these tests on a non-browser platform that doesn't have a DOM or\nwhose DOM-emulation doesn't support the full HTMLElement
API.
Angular relies on the DebugElement
abstraction to work safely across all supported platforms.\nInstead of creating an HTML element tree, Angular creates a DebugElement
tree that wraps the native elements for the runtime platform.\nThe nativeElement
property unwraps the DebugElement
and returns the platform-specific element object.
Because the sample tests for this guide are designed to run only in a browser,\na nativeElement
in these tests is always an HTMLElement
\nwhose familiar methods and properties you can explore within a test.
Here's the previous test, re-implemented with fixture.debugElement.nativeElement
:
The DebugElement
has other methods and properties that\nare useful in tests, as you'll see elsewhere in this guide.
You import the DebugElement
symbol from the Angular core library.
Although the tests in this guide all run in the browser,\nsome apps might run on a different platform at least some of the time.
\nFor example, the component might render first on the server as part of a strategy to make the application launch faster on poorly connected devices. The server-side renderer might not support the full HTML element API.\nIf it doesn't support querySelector
, the previous test could fail.
The DebugElement
offers query methods that work for all supported platforms.\nThese query methods take a predicate function that returns true
when a node in the DebugElement
tree matches the selection criteria.
You create a predicate with the help of a By
class imported from a\nlibrary for the runtime platform. Here's the By
import for the browser platform:
The following example re-implements the previous test with\nDebugElement.query()
and the browser's By.css
method.
Some noteworthy observations:
\nBy.css()
static method selects DebugElement
nodes\nwith a standard CSS selector.DebugElement
for the paragraph.When you're filtering by CSS selector and only testing properties of a browser's native element, the By.css
approach may be overkill.
It's often easier and more clear to filter with a standard HTMLElement
method\nsuch as querySelector()
or querySelectorAll()
.