Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 3

Unit Testing in Angular

1. Component
How to Test Component .

counter.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css']
})
export class CounterComponent {
counter : number;
constructor( ) {
this.counter = 0;
}

inc(){
this.counter++;
}

dec(){
this.counter--;
}

counter.component.html
<p>
Number : {{counter}}
</p>

<button (click) ="inc();">Increment</button>


<button (click) ="dec();">Decrement</button>
counter.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { CounterComponent } from './counter.component';


import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';

describe('CounterComponent', () => {
let component: CounterComponent;
let fixture: ComponentFixture<CounterComponent>;
let debugElement: DebugElement;
let HtmlElement: HTMLElement;

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

beforeEach(() => {
fixture = TestBed.createComponent(CounterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
debugElement = fixture.debugElement.query(By.css('p'));
HtmlElement = debugElement.nativeElement;
});

it('should create', () => {


expect(component).toBeTruthy();
});

it('should display the current number of the counter', () => {


const initialvalue = component.counter;
// expect(HtmlElement.textContent).toEqual('Number : 0');
expect(initialvalue).toBe(0);
});

it('should increment the counter number by one', () => {


const initialvalue = component.counter;
component.inc();
fixture.detectChanges();
const newvalue = component.counter;
expect(newvalue).toBeGreaterThan(initialvalue);
});

it('should decrement the counter number by one', () => {


const initialvalue = component.counter;
component.dec();
fixture.detectChanges();
const newvalue = component.counter;
expect(newvalue).toBeLessThan(initialvalue);
});

});

2.HTTPClient Module Testing

You might also like