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

  1. describe(…), beforeEach(…), afterEach(…)
  2. it(…), expect(…).toEqual(…)
  3. component = new SomeComponent();

Testing components with TestBed

Basic configuration

  1. TestBed.configureTestingModule(…)
  2. fixture = TestBed.createComponent(Component);
  3. fixture.componentInstance;
 

DOM testing

  1. fixture.detectChanges() 
  2. nativeElement = fixture.nativeElement
  3. debugElement: DebugElement = fixture.debugElement
  4. debugElement.query() & By.css(…)
  5. Unwrap: nativeElement = debugElement.nativeElement
  6. component = fixture.componentInstance;
 

DOM with dependencies

TestBed.configureTestingModule({
    declarations: [ SomeComponent, OtherComponent ],
    providers: [{ provide: Service, useValue: serviceMock }]
});

What to test

  1. ngIf, ngFor 
  2. disabled, hidden  
  3. @Input(), @Output()
  4. Component lifecycle hooks (ngOnInit, ngOnDestroy and others)
  5. 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

  1. Shallow testing
  2. Stub components
  3. NO_ERRORS_SCHEMA
  4. CUSTOM_ELEMENTS_SCHEMA
 

Useful tips

  1. fdescribe, fit – execute only these tests
  2. xdescribe, xit – skip these tests
  3. Use helpers for repeated actions
  4. Group tests into ‘describe’ blocks
  5. Keep test blocks as independent as possible
 

Useful links

Q & A

Angular. Unit Testing

By Pavel Razuvalau

Angular. Unit Testing

  • 838