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 Value Converter
  • Writing Tests for Value Converters
  • Setting Up the Test Environment
  • Test Implementation
  • Conclusion

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Testing

Testing value converters

PreviousTesting componentsNextWorking with the fluent API

Last updated 1 year ago

Was this helpful?

Value converters in Aurelia 2 are an essential feature that allows you to create custom logic to transform data for display in your views. When it comes to testing value converters, you should aim for a mix of unit and integration tests to ensure that they function correctly both in isolation and when integrated within a view.

Example Value Converter

Let's start with a simple value converter that transforms a string to uppercase:

to-uppercase.ts
import { valueConverter } from 'aurelia';

@valueConverter('toUpper')
export class ToUpper {
    toView(value: string): string {
        return value ? value.toUpperCase() : value;
    }
}

This value converter checks if the input is a string and, if so, transforms it to uppercase. If the input is null or undefined, it simply returns the input without modification.

Writing Tests for Value Converters

When testing value converters, we will create unit tests to validate the converter logic and integration tests to ensure the converter works as expected within an Aurelia view.

Setting Up the Test Environment

Before writing tests, make sure to set up the test environment as described in the .

Test Implementation

Create a test file for your value converter, such as to-uppercase.spec.ts. Here we will write tests for both unit and integration scenarios.

to-uppercase.spec.ts
import { createFixture } from '@aurelia/testing';
import { ToUpper } from './to-upper';
import { bootstrapTestEnvironment } from './path-to-your-initialization-code';

describe('ToUpper value converter', () => {
    let sut: ToUpper;

    beforeAll(() => {
        // Initialize the test environment before running the tests
        bootstrapTestEnvironment();
        sut = new ToUpper();
    });

    // Unit Tests
    it('returns null for null input', () => {
        expect(sut.toView(null)).toBeNull();
    });

    it('transforms provided string to uppercase', () => {
        expect(sut.toView('rOb wAs hErE')).toBe('ROB WAS HERE');
    });

    it('transforms provided string containing numbers to uppercase', () => {
        expect(sut.toView('rob is here 123')).toBe('ROB IS HERE 123');
    });

    // Integration Test
    it('works within a view', async () => {
        const { appHost, startPromise, tearDown } = createFixture(
            '<div>${text | toUpper}</div>',
            class App {
                text = 'rob is here 123';
            },
            [ToUpper]
        );

        await startPromise;

        expect(appHost.textContent).toBe('ROB IS HERE 123');

        await tearDown();

        expect(appHost.textContent).toBe('');
    });
});

In the unit tests, we instantiate the ToUpper value converter and directly call its toView method with different inputs to verify the output. We test with null, a valid string, and a string with numbers to cover various scenarios.

The integration test uses the createFixture function to test the value converter within an Aurelia view. We define a mock component with a text property bound to the view and apply the toUpper value converter. We then assert that the rendered text content is transformed as expected.

Good tests cover a range of scenarios, including expected successes, expected failures, and edge cases. This comprehensive approach ensures your value converter handles all types of inputs gracefully.

This method of testing can be applied to any class-based code in Aurelia 2. While the fixture bootstrap functionality is excellent for testing component output and behavior, it's not always necessary for unit testing pure code logic.

Conclusion

Testing value converters is an essential step in ensuring the reliability and robustness of your Aurelia 2 applications. By writing both unit and integration tests, you can confidently verify that your value converters perform correctly in isolation and within the context of an Aurelia view.

Overview Section