For the complete documentation index, see llms.txt. This page is also available as Markdown.

Testing Custom Elements

Basic Component Test

Let's break down a comprehensive example of testing a custom element:

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

describe('UserProfile Component', () => {
  let component;

  // Custom element to be tested
  class UserProfile {
    @bindable firstName;
    @bindable lastName;

    get fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }

  beforeEach(() => {
    // Stage the component for testing
    component = StageComponent
      .withResources(PLATFORM.moduleName('user-profile'))
      .inView('<user-profile first-name.bind="firstName" last-name.bind="lastName"></user-profile>')
      .boundTo({
        firstName: 'John',
        lastName: 'Doe'
      });
  });

  it('should render full name correctly', done => {
    component.create(bootstrap).then(() => {
      const nameElement = document.querySelector('.full-name');
      expect(nameElement.textContent).toBe('John Doe');
      done();
    }).catch(done.fail);
  });

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

Note the use of PLATFORM.moduleName() for better compatibility with module loaders like Webpack.

Detailed Binding and Property Tests

Testing bindable properties in our component.

Lifecycle Method Testing

Here we manually control the lifecycle so we can decide when the lifecycle methods get fired.

Complex Binding Scenarios

Testing two-way and computed bindings.

Best Practices for Component Testing

  • Always use PLATFORM.moduleName() for resources

  • Dispose of components in afterEach()

  • Use done() or return a Promise for async tests

  • Test various binding scenarios

  • Mock external dependencies

  • Check both initial state and state after updates

Common Pitfalls to Avoid

  • Don't rely on implementation details

  • Avoid testing private methods

  • Use meaningful test descriptions

  • Handle async operations carefully

  • Clean up DOM between tests

Last updated

Was this helpful?