Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Angular Testing Kit

DZone's Guide to

The Angular Testing Kit

Testing a Simple Component Testing Template Test a Simple Class Mock Event Service Testing https://semaphoreci.com/community/tutorials/testing-services-in-an...

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

Testing a Simple Component


import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent Tests', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it('should render greeting', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome!');
  }));
});

Testing Template

// EX1
import { async, TestBed } from '@angular/core/testing';
import { SomeComponent } from './some.component';

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [
      SomeComponent
    ],
    imports: [
      // HttpModule, etc.
    ],
    providers: [
      // { provide: ServiceA, useClass: TestServiceA }
    ]
  });
});

it('should do something', async(() => {
  TestBed.compileComponents().then(() => {
    const fixture = TestBed.createComponent(SomeComponent);

    // Access the dependency injected component instance
    const app = fixture.componentInstance;
    expect(app.something).toBe('something');

    // Access native element
    const element = fixture.nativeElement;

    // detect changes
    fixture.detectChanges();
    expect(element.textContent).toContain('something');
  });
}));


// EX2
it('should get quote', () => {

  fixture.debugElement.componentInstance.getQuote();
  fixture.detectChanges();
  var compiled = fixture.debugElement.nativeElement;

  expect(compiled.querySelector('div'))
    .toHaveText('Test Quote'); 
});


// EX3
import {TestBed, ComponentFixture, inject, async} from '@angular/core/testing';
import {LandingComponent, User} from './landing.component';
import {Component, DebugElement} from "@angular/core";
import {By} from "@angular/platform-browser";


describe('Component: Landing', () => {

  let component: LoginComponent;
  let fixture: ComponentFixture;
  let submitEl: DebugElement;
  let usernameEl: DebugElement;

  beforeEach(() => {

    // refine the test module by declaring the test component
    TestBed.configureTestingModule({
      declarations: [LandingComponent]
    });


    // create component and test fixture
    fixture = TestBed.createComponent(LandingComponent);

    // get test component from the fixture
    component = fixture.componentInstance;

    submitEl = fixture.debugElement.query(By.css('button'));
    usernameEl = fixture.debugElement.query(By.css('input[type=text]'));
  });

  it('Setting enabled to false disabled the submit button', () => {
    component.enabled = false;
    fixture.detectChanges();
    expect(submitEl.nativeElement.disabled).toBeTruthy();
  });

  it('Setting enabled to true enables the submit button', () => {
    component.enabled = true;
    fixture.detectChanges();
    expect(submitEl.nativeElement.disabled).toBeFalsy();
  });

  it('Entering email and password emits loggedIn event', () => {
    let user: User;
    usernameEl.nativeElement.value = "test";

    // Subscribe to the Observable and store the user in a local variable.
    component.loggedIn.subscribe((value) => user = value);

    // This sync emits the event and the subscribe callback gets executed above
    submitEl.triggerEventHandler('click', null);

    // Now we can check to make sure the emitted value is correct
    expect(user.name).toBe("test");
  });
});

Test a Simple Class

import { countries } from './countries';
import { Util } from './util';

let testClass: Util = null;
describe('Util Tests', () => {
  beforeEach(() => {
    testClass = new Util();
  });

  it('should ensure getCountries is based on countries file', () => {
    const actual = testClass.getCountries;
    expect(actual[0].id).toEqual(countries[0].id);
  });
});

import { countries } from './countries';
export class Util {

  public countries: any[] = countries;

  public getProducts() {
    return this.countries;
  }
}

Mock Event

  const mockEvent: Event = {
    srcElement: {
      classList: ''
    },
    charCode: 64,
    stopPropagation: ( ( e: any ) => { /**/ }),
    preventDefault: ( ( e: any ) => { /**/ }),
  };

Service Testing

Template Testing

GAnalytics

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

Topics:
web dev ,angular ,tutorial ,web application testing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}