Home  > Resources  > Blog

Angular Unit testing with Jasmine

 
October 22, 2021 by David Chung
Category: Angular

This tutorial is adapted from the Web Age course Angular Unit Testing with Jasmine.

1.1 Software Testing

Verifying that the application meets its requirements

  • Identifies bugs
  • Reduces developments costs
  • Speeds time to market
  • Improves user satisfaction

1.2 Types of tests

TestType

Description

UX User Experience
UAT User Acceptance
Regression New/Changed Features
Stress Extreme Throughput/Capacity
Performance Measure Under Varying Load
Functional Functional Requirements
Integration Multiple Components
Unit Individual Unit

1.3 Test Pyramid

Tests can often be broken down into coarser categories

Top

  • Slower
  • More Expensive
  • Less Frequent

Bottom

  • Faster
  • Less Expensive
  • More Frequent

1.4 Unit Tests

Test small software units like Components, Services, Pipes.  Unit tests define tests for Happy Path and Exceptions/Failure. Unit Tests should be automated as part of the Build CI/CD process

1.5 Jasmine, Karma and Angular

  • Angular – TypeScript/JavaScript framework for building GUI applications
  • Jasmine – Unit testing framework for Angular
  • Karma – Test runner for Angular

1.6 Jasmine

  • Unit test framework for JavaScript/TypeScript
  • Tests are written in Jasmine
  • Tests all Angular artifacts
  • Synchronous and Asynchronous tests

1.7 Karma

  • Test runner works with Jasmine (and other test tools)
  • Runs test in real or simulated devices/browsers
  • Controlled by command line or IDE
  • Automatically runs tests on changes to source files
  • Works with CI/CD tools

1.8 Basic Terminology

  • Test Suite – a collection of specs
  • Spec – individual test
  • Expectation – assertion about a value or result
  • Matcher – code to evaluate the expected result

1.9 Test Suite

Filename matches the filename of the artifact being tested with spec

     app.salestax.service.ts
     app.salestax.service.spec.ts
  • Built using the describe() function

The function takes two parameters:

  • A string (used as the suite title)
  • A function or arrow (lambda) function that contains the specs

Example

    describe( 'a test suite', () => {
      // insert tests/specs here
    })

Note

Test suites may be nested

1.10 Spec

  • A single unit test
  • Built using the it() function
  • The function takes two parameters: A string (used as the suite title) and A function or arrow (lambda) function that contains the specs

Example

    it( 'should add 2+2=4', () => {
      expect(2+2).toBe(4)
    })

Note

If the arrow function evaluates to true the spec succeeds.

1.11 Assertion

Asserts that a statement is true

  • the result is 0
  • the service has been created
  • the result is true

Uses the expect() function and chain matcher function

    expect(service.isComplete()).toBeTrue()
    expect(app.title).toEqual('Jasmine Test')

1.12 Matchers

toBe toBeUndefined
toBeCloseTo toContain
toBeDefined toEqual
toBeFalsey toHaveBeenCalled
toBeGreaterThan toHaveBeenCalledWith
toBeLessThan toMatch
toBeNaN toThrow
toBeNull toThrowError
toBeTruthy  

Note

In addition to these pre-defined matchers, you can define your own matcher function.

1.13 Setup and Teardown

Test suites may define (optional) functions to be called around specs.

Each function takes an arrow function as a parameter

The arrow function performs the action

Functions

  • beforeAll() – invoked before all specs
  • beforeEach() – invoked before each spec
  • afterEach() – invoked after each spec
  • afterAll() – invoked after all specs

1.14 A Test Suite

    describe('a test suite', () => {
      let order = { 'widgets':2 }
      beforeAll( () => {
        order = 4
      })
      beforeEach( () => {
        order = 6
      })
      it( 'should have widgets', () => {
        expect(order).toBeTruthy() // succeeds
      })
      it( 'should have widgets', () => {
        expect(order).toBe(4) // fails 
      })
    })

1.15 Auto-Generated Angular Test Suites

When you create an Angular application the CLI creates a test suite.

The specs verify

  • that the component has been created
  • that the title is set in the component class
  • that the title is rendered in the default template

Angular creates a simple test suite for all artifacts you create with the CLI and uses these as the framework in which to build your own more meaningful tests.

1.16 Run a Test


1.17 Summary

In this tutorial, we discussed

  • Core Concepts
  • Test Suites
  • Specs
  • Matchers
  • Auto-Generated Angular Test Suites

Follow Us

Blog Categories