Karma

  • Karma is the test runner that is used to execute Angular unit tests
  • You can manually install and configure Karma
  • Karma is installed and configured by default when you create a project with the Angular CLI
  • Karma is configured via the karma.conf.js file
  • Tests (specs) are identified with a .spec.ts naming convention

Debugging with Karma

  • Use the developer console in the Karma browser window to debug your unit tests
  • If something is throwing an error, you will generally see it in the console
  • If you need to step through something, you can do some from a breakpoint in the developer tools
  • Logging to the console is also a handy tool for observing data and events

Examples

Simple Test

describe('First spec', () => {
  it('should pass', () => {
    expect(true).toBeTruthy();
  });
});

Basic Component Test

  1. Configure Module
  2. Create Fixture
  3. Get Component Instance
// Component
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-simple',
  template: '<h1>Hello {{subject}}!</h1>'
})
export class SimpleComponent implements OnInit {
  subject: string = 'world';
  constructor() { }
  ngOnInit() { }
}

Configure Module

TestBed
  • The most important piece of the Angular testing utilities
  • Creates an Angular testing module which is an @NgModule class
  • You can configure the module by calling TestBed.configureTestingModule
  • Configure the testing module in the BeforeEach so that it gets reset before each spec
import { TestBed } from '@angular/core/testing';
import { SimpleComponent } from './simple.component';

describe('SimpleComponent', () => {
  let component: SimpleComponent;
  let fixture: any;

  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      declarations: [ SimpleComponent ]
    });
  });
});

Create Fixture

  • TestBed.createComponent creates an instance of the component under test
  • Returns a component test fixture
  • Calling createComponent closes the TestBed from further configuration
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SimpleComponent } from './simple.component';

describe('SimpleComponent', () => {
  let component: SimpleComponent;
  let fixture: ComponentFixture<SimpleComponent>;
  
  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      declarations: [ SimpleComponent ]
    })
    .createComponent(SimpleComponent);
  });
});