1/10/17

Unit Tests In Angular2 - part 2 (The Component)

Testing The Component

In previous post we've learned how to test the model (Simple javascript object) and the Service in angular2. Now I think' we ready for next step:

How To Test The Component

Lets say we have a User Component which should display the full name of some user:
(user-component.ts):


import { Component,  Input} from '@angular/core';
import {UserModel} from './user-model'
@Component({
    selector: 'user-component',
    template:   `{{ user.fullname() }}`
})
export class UserComponent {
    @Input() user:UserModel;
}

This component contains @input annotation - which means the parameter from outside (named user) should be set

The Test

As in case of Service we should start with setup the module with testBed util:
(user-component.spec.ts):



import {UserComponent} from './user-component'
import {UserModel} from './user-model'
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

describe('UserComponent tests', function () {
  let de: DebugElement;
  let comp: UserComponent;
  let fixture: ComponentFixture;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [  UserComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UserComponent);
    comp = fixture.componentInstance;
    comp.user = new UserModel('Vasia','Kozlov')// <--here we passing the outer parameter
    de = fixture.debugElement.query(By.css('span'));
  });

  it('should create component', () => expect(comp).toBeDefined() );

  it('should have fullname of user displayed inside "span" tag', () => {
    fixture.detectChanges();
    const h1 = de.nativeElement;
    expect(h1.innerText).toMatch(/Vasia Kozlov/i,
      ' should state user Full Name');
  });
});

As you can see - the outer parameter passed using fixture.componentInstance helper
You can view the running code on the plunker

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...