Angular
Unit Testing
What does "Unit Testing" mean?
It's pretty simple
function multiply(a, b) {
return a * b;
}
console.log(multiply(2, 3) === 6);
Why do we need unit testing?
Unit testing
- Helps to design
- Simplifies refactoring
- Documents code behavior
- Helps to keep us sane
Testing with ng-cli



It works out of the box
ng test
Pretty simple, right?
First look
- describe(…), beforeEach(…), afterEach(…)
- it(…), expect(…).toEqual(…)
- component = new SomeComponent();
Testing components with TestBed
Basic configuration
- TestBed.configureTestingModule(…)
- fixture = TestBed.createComponent(Component);
- fixture.componentInstance;
DOM testing
- fixture.detectChanges()
- nativeElement = fixture.nativeElement;
- debugElement: DebugElement = fixture.debugElement
- debugElement.query() & By.css(…)
- Unwrap: nativeElement = debugElement.nativeElement
- component = fixture.componentInstance;
DOM with dependencies
TestBed.configureTestingModule({
declarations: [ SomeComponent, OtherComponent ],
providers: [{ provide: Service, useValue: serviceMock }]
});What to test
- ngIf, ngFor
- disabled, hidden
- @Input(), @Output()
- Component lifecycle hooks (ngOnInit, ngOnDestroy and others)
- Pipes, directives and how they affect DOM
Test host approach
Test host approach
@Component({
template: `
<app-publication-card
[publication]="publication(like)="onLiked($event)">
</app-publication-card>`
})
class TestHostComponent {
// all additional logic required for testing
}Nested component tests
<section>
<app-user-picture></app-user-picture>
<app-user-info></app-user-info>
<app-user-menu></app-user-menu>
<app-publication-card *ngFor="let publication of userPublications" [publication]="publication">
</app-publication-card>
</section>Nested component tests
Nested component tests approaches
- Shallow testing
- Stub components
- NO_ERRORS_SCHEMA
- CUSTOM_ELEMENTS_SCHEMA
Useful tips
- fdescribe, fit – execute only these tests
- xdescribe, xit – skip these tests
- Use helpers for repeated actions
- Group tests into ‘describe’ blocks
- Keep test blocks as independent as possible
Useful links
Angular testing guide
https://angular.io/guide/testing
Why do we need unit tests
https://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/
Key qualities of a good unit test
https://www.kenneth-truyers.net/2012/12/15/key-qualities-of-a-good-unit-test/
FunFunFunction on unit testing
https://www.youtube.com/watch?v=Eu35xM76kKY
More examples with unit testing
Q & A
Angular. Unit Testing
By Pavel Razuvalau
Angular. Unit Testing
- 1,021