LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Example Custom Attribute
  • Testing the Custom Attribute
  • Test Setup
  • Writing Tests
  • Testing Approach
  • Conclusion

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Testing

Testing attributes

Testing custom attributes in Aurelia is analogous to testing components, with the primary difference being that custom attributes do not have a view template. They are, however, responsible for modifying the behavior or appearance of existing DOM elements. By leveraging the same testing techniques used for components, we can effectively validate the functionality of our custom attributes.

Example Custom Attribute

Let's consider a ColorSquareCustomAttribute that we previously created. This attribute applies a color border and sets the size of an element, resulting in a square of uniform dimensions with a colored background.

color-square.ts
import { bindable, customAttribute, INode, resolve } from 'aurelia';

@customAttribute('color-square')
export class ColorSquareCustomAttribute {
  @bindable color: string = 'red';
  @bindable size: string = '100px';

  private element: HTMLElement = resolve(INode)
  constructor() {
    this.element.style.width = this.size;
    this.element.style.height = this.size;
    this.element.style.backgroundColor = this.color;
  }

  bound() {
    this.element.style.width = this.size;
    this.element.style.height = this.size;
    this.element.style.backgroundColor = this.color;
  }

  colorChanged(newColor: string) {
    this.element.style.backgroundColor = newColor;
  }

  sizeChanged(newSize: string) {
    this.element.style.width = newSize;
    this.element.style.height = newSize;
  }
}

Testing the Custom Attribute

We will now write tests to ensure that the ColorSquareCustomAttribute behaves as expected when applied to an element.

Test Setup

Writing Tests

Create a test file for your custom attribute, such as color-square.spec.ts, and use the following example as a guide:

color-square.spec.ts
import { createFixture } from '@aurelia/testing';
import { ColorSquareCustomAttribute } from './color-square';
import { bootstrapTestEnvironment } from './path-to-your-initialization-code';

describe('ColorSquareCustomAttribute', () => {
  beforeAll(() => {
    // Initialize the test environment before running the tests
    bootstrapTestEnvironment();
  });

  it('applies default width and color', async () => {
    const { appHost, startPromise, tearDown } = createFixture(
      '<div id="attributeel" color-square></div>',
      class App {},
      [ColorSquareCustomAttribute]
    );

    await startPromise;

    const el = appHost.querySelector('#attributeel') as HTMLElement;

    expect(el.style.width).toBe('100px');
    expect(el.style.height).toBe('100px');
    expect(el.style.backgroundColor).toBe('red');

    await tearDown();
  });

  it('reacts to color changes', async () => {
    const { appHost, component, startPromise, tearDown } = createFixture(
      '<div color-square="color.bind: newColor; size.bind: newSize"></div>',
      class App {
        newColor = 'blue';
        newSize = '150px';
      },
      [ColorSquareCustomAttribute]
    );

    await startPromise;

    const colorSquareAttribute = component.viewModel as ColorSquareCustomAttribute;

    // Test initial state
    expect(appHost.firstElementChild.style.backgroundColor).toBe('blue');
    expect(appHost.firstElementChild.style.width).toBe('150px');
    expect(appHost.firstElementChild.style.height).toBe('150px');

    // Change color property
    colorSquareAttribute.color = 'green';
    colorSquareAttribute.colorChanged('green', 'blue');

    expect(appHost.firstElementChild.style.backgroundColor).toBe('green');

    await tearDown();
  });

  // Additional tests...
});

In the first test, we verify that the default size and color are applied to an element when the custom attribute is used without any bindings. In the second test, we bind the color and size properties and then change the color to ensure the colorChanged method updates the element's style as expected.

Testing Approach

As with components, we use createFixture to set up our test environment. The first argument is the HTML view where we use our custom attribute. The second argument is the view model, which can define values to bind in our view model if needed. The third argument specifies any dependencies required by our tests, such as custom elements, value converters, or attributes.

Conclusion

Testing custom attributes in Aurelia 2 is essential to ensure they correctly manipulate DOM elements as intended. By setting up a proper testing environment, creating fixtures, and writing assertions, we can confidently verify that our custom attributes perform their duties correctly. Always remember to clean up your tests to maintain a pristine testing state.

PreviousTestingNextTesting components

Last updated 1 year ago

Was this helpful?

Before writing tests, ensure that your test environment is properly configured. The setup for testing custom attributes is the same as for components, so refer to the section.

Overview