Examples of Tests
Let's explore the common examples of tests in Angular.
We'll cover the following...
Common test scenarios
Let’s move on to looking at some examples of the types of tests we may have in our Angular applications. While the functionality of each Angular application is different, there are some common types of tests we may write in our application.
The scenarios we’re going to look at are as follows:
- A test that accesses the template of a component
- A test that checks the
@Input()
and@Output()
attributes of the component - A test for a service
Tests for a template of a component
In this example, we’re going to look at how to access elements within a template to see if there are changes to them based on functionality in the component class. Here is an example test spec file that checks for changes in the template:
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ExampleComponent } from './example.component';
describe('DomTestingComponent', () => {
let component: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ExampleComponent]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should not have the display the users name', () => {
const usernameEl = fixture.debugElement.query(By.css('.username'));
expect(usernameEl).toBeNull();
});
it('should display the users name when set', () => {
component.username = 'Test User';
fixture.detectChanges();
fixture.whenStable().then(() => {
const usernameEl =
fixture.debugElement.query(By.css('.username'));
expect(usernameEl).not.toBeNull();
});
});
});
We can access the template through the fixture, which, as we know, is set via the TestBed
class generating a wrapper for the component and the template. Then, to access the value of the HTML element, we’re using CSS to find the class of the HTML element that contains the username:
const usernameEl = fixture.debugElement.query(By.css('.username'));
This line accesses the HTML element, using the By.css()
function to find the matching element with the CSS class. When we have access to this HTML element, we can check ...