Unit Testing

Unit testing in Aurelia allows you to verify individual components, services, and behaviors in isolation. Aurelia's architecture is designed with testability in mind — its dependency injection system makes it straightforward to mock dependencies and test components independently.

Getting Started

Aurelia provides the aurelia-testing library, which gives you tools to stage and test custom elements and attributes in a mini Aurelia application environment.

Installation

npm install aurelia-testing --save-dev

Basic Test Setup

A typical unit test uses StageComponent from aurelia-testing along with a test runner like Jest or Jasmine:

import { StageComponent } from 'aurelia-testing';
import { bootstrap } from 'aurelia-bootstrapper';

describe('MyComponent', () => {
  let component;

  beforeEach(() => {
    component = StageComponent
      .withResources('my-component')
      .inView('<my-component></my-component>');
  });

  afterEach(() => {
    component.dispose();
  });

  it('should render', done => {
    component.create(bootstrap).then(() => {
      expect(document.querySelector('my-component')).not.toBeNull();
      done();
    }).catch(done.fail);
  });
});

Testing Without the DOM

For view-models that don't require DOM interaction, you can test them directly:

What's Covered

The following sections provide detailed guidance on testing specific aspects of Aurelia applications:

circle-info

Always call component.dispose() in your afterEach block to clean up the DOM and prevent test pollution between test cases.

Last updated

Was this helpful?