dojo dragon main logo

Test Renderer

Dojo provides a simple and type safe test renderer for shallowly asserting the expected output and behavior from a widget. The test renderer's API has been designed to encourage unit testing best practices from the outset to ensure high confidence in your Dojo application.

Working with assertions and the test renderer is done using wrapped test nodes that are defined in the assertion structure, ensuring type safety throughout the testing life-cycle.

The expected structure of a widget is defined using an assertion and passed to the test renderer's .expect() function which executes the assertion.

src/MyWidget.spec.tsx

import { tsx } from '@dojo/framework/core/vdom';
import renderer, { assertion } from '@dojo/framework/testing/renderer';

import MyWidget from './MyWidget';

const baseAssertion = assertion(() => (
    <div>
        <h1>Heading</h1>
        <h2>Sub Heading</h2>
        <div>Content</div>
    </div>
));

const r = renderer(() => <MyWidget />);

r.expect(baseAssertion);

Wrapped Test Nodes

In order for the test renderer and assertions to be able to identify nodes within the expected and actual node structure a special wrapping node must be used. The wrapped nodes can get used in place of the real node in the expected assertion structure, maintaining all the correct property and children typings.

To create a wrapped test node use the wrap function from @dojo/framework/testing/renderer:

src/MyWidget.spec.tsx

import { wrap } from '@dojo/framework/testing/renderer';

import MyWidget from './MyWidget';

// Create a wrapped node for a widget
const WrappedMyWidget = wrap(MyWidget);

// Create a wrapped node for a vnode
const WrappedDiv = wrap('div');

The test renderer uses the location of a wrapped test node in the expected tree to attempt to perform any requested actions (either r.property() or r.child()) on the actual output of the widget under test. If the wrapped test node does not match the corresponding node in the actual output tree then no action will be performed and the assertion will report a failure.

Note: Wrapped test nodes should only be used once within an assertion, if the same test node is detected more than once during an assertion an error will be thrown and the test fail.

Assertion

Assertions get used to build the expected widget output structure to use with renderer.expect(). The assertion expose a wide range of APIs that enable the expected output to vary between tests.

Given a widget that renders output differently based on property values:

src/Profile.tsx

import { create, tsx } from '@dojo/framework/core/vdom';

import * as css from './Profile.m.css';

export interface ProfileProperties {
    username?: string;
}

const factory = create().properties<ProfileProperties>();

const Profile = factory(function Profile({ properties }) {
    const { username = 'Stranger' } = properties();
    return <h1 classes={[css.root]}>{`Welcome ${username}!`}</h1>;
});

export default Profile;

Create an assertion using @dojo/framework/testing/renderer#assertion:

src/Profile.spec.tsx

const { describe, it } = intern.getInterface('bdd');
import { tsx } from '@dojo/framework/core/vdom';
import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';

import Profile from '../../../src/widgets/Profile';
import * as css from '../../../src/widgets/Profile.m.css';

// Create a wrapped node
const WrappedHeader = wrap('h1');

// Create an assertion using the `WrappedHeader` in place of the `h1`
const baseAssertion = assertion(() => <WrappedHeader classes={[css.root]}>Welcome Stranger!</WrappedHeader>);

describe('Profile', () => {
    it('Should render using the default username', () => {
        const r = renderer(() => <Profile />);

        // Test against the base assertion
        r.expect(baseAssertion);
    });
});

To test when a username property gets passed to the Profile widget, we could create a new assertion with the updated expected username. However, as a widget increases its functionality, recreating the entire assertion for each scenario becomes verbose and unmaintainable, as any changes to the common widget structure would require updating every assertion.

To help avoid the maintenance overhead and reduce duplication, assertions offer a comprehensive API for creating variations from a base assertion. The assertion API uses wrapped test nodes to identify the node in the expected structure to update.

src/Profile.spec.tsx

const { describe, it } = intern.getInterface('bdd');
import { tsx } from '@dojo/framework/core/vdom';
import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';

import Profile from '../../../src/widgets/Profile';
import * as css from '../../../src/widgets/Profile.m.css';

// Create a wrapped node
const WrappedHeader = wrap('h1');

// Create an assertion using the `WrappedHeader` in place of the `h1`
const baseAssertion = assertion(() => <WrappedHeader classes={[css.root]}>Welcome Stranger!</WrappedHeader>);

describe('Profile', () => {
    it('Should render using the default username', () => {
        const r = renderer(() => <Profile />);

        // Test against the base assertion
        r.expect(baseAssertion);
    });

    it('Should render using the passed username', () => {
        const r = renderer(() => <Profile username="Dojo" />);

        // Create a variation of the base assertion
        const usernameAssertion = baseAssertion.setChildren(WrappedHeader, () => ['Dojo']);

        // Test against the username assertion
        r.expect(usernameAssertion);
    });
});

Creating assertions from a base assertion means that if there is a change to the default widget output, only a change to the baseAssertion is required to update all the widget's tests.

Assertion API

assertion.setChildren()

Returns a new assertion with the new children either pre-pended, appended or replaced depending on the type passed.

.setChildren(
  wrapped: Wrapped,
  children: () => RenderResult,
  type: 'prepend' | 'replace' | 'append' = 'replace'
): AssertionResult;

assertion.append()

Returns a new assertion with the new children appended to the node's existing children.

.append(wrapped: Wrapped, children: () => RenderResult): AssertionResult;

assertion.prepend()

Returns a new assertion with the new children pre-pended to the node's existing children.

.prepend(wrapped: Wrapped, children: () => RenderResult): AssertionResult;

assertion.replaceChildren()

Returns a new assertion with the new children replacing the node's existing children.

.replaceChildren(wrapped: Wrapped, children: () => RenderResult): AssertionResult;

assertion.insertSiblings()

Returns a new assertion with the passed children inserted either before or after depending on the type passed.

.insertSiblings(
  wrapped: Wrapped,
  children: () => RenderResult,
  type: 'before' | 'after' = 'before'
): AssertionResult;

assertion.insertBefore()

Returns a new assertion with the passed children inserted before the existing node's children.

.insertBefore(wrapped: Wrapped, children: () => RenderResult): AssertionResult;

assertion.insertAfter()

Returns a new assertion with the passed children inserted after the existing node's children.

.insertAfter(wrapped: Wrapped, children: () => RenderResult): AssertionResult;

assertion.replace()

Returns a new assertion replacing the existing node with the node that is passed. Note that if you need to interact with the new node in either assertions or the test renderer, it should be a wrapped test node.

.replace(wrapped: Wrapped, node: DNode): AssertionResult;

assertion.remove()

Returns a new assertion removing the target wrapped node completely.

.remove(wrapped: Wrapped): AssertionResult;

assertion.setProperty()

Returns a new assertion with the updated property for the target wrapped node.

.setProperty<T, K extends keyof T['properties']>(
  wrapped: Wrapped<T>,
  property: K,
  value: T['properties'][K]
): AssertionResult;

assertion.setProperties()

Returns a new assertion with the updated properties for the target wrapped node.

.setProperties<T>(
  wrapped: Wrapped<T>,
  value: T['properties'] | PropertiesComparatorFunction<T['properties']>
): AssertionResult;

A function can be set in place of the properties object to return the expected properties based off the actual properties.

Triggering Properties

In addition to asserting the output from a widget, widget behavior can be tested by using the renderer.property() function. The property() function takes a wrapped test node and the key of a property to call before the next call to expect().

src/MyWidget.tsx

import { create, tsx } from '@dojo/framework/core/vdom';
import icache from '@dojo/framework/core/middleware/icache';
import { RenderResult } from '@dojo/framework/core/interfaces';

import MyWidgetWithChildren from './MyWidgetWithChildren';

const factory = create({ icache }).properties<{ onClick: () => void }>();

export const MyWidget = factory(function MyWidget({ properties, middleware: { icache } }) {
    const count = icache.getOrSet('count', 0);
    return (
        <div>
            <h1>Header</h1>
            <span>{`${count}`}</span>
            <button
                onclick={() => {
                    icache.set('count', icache.getOrSet('count', 0) + 1);
                    properties().onClick();
                }}
            >
                Increase Counter!
            </button>
        </div>
    );
});

src/MyWidget.spec.tsx

const { describe, it } = intern.getInterface('bdd');
import { tsx } from '@dojo/framework/core/vdom';
import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';
import * as sinon from 'sinon';

import MyWidget from './MyWidget';

// Create a wrapped node for the button
const WrappedButton = wrap('button');

const WrappedSpan = wrap('span');

const baseAssertion = assertion(() => (
    <div>
      <h1>Header</h1>
      <WrappedSpan>0</WrappedSpan>
      <WrappedButton onclick={() => {
        icache.set('count', icache.getOrSet('count', 0) + 1);
        properties().onClick();
      }}>Increase Counter!</button>
    </WrappedButton>
));

describe('MyWidget', () => {
    it('render', () => {
        const onClickStub = sinon.stub();
        const r = renderer(() => <MyWidget onClick={onClickStub} />);

        // assert against the base assertion
        r.expect(baseAssertion);

        // register a call to the button's onclick property
        r.property(WrappedButton, 'onclick');

        // create a new assertion with the updated count
        const counterAssertion = baseAssertion.setChildren(WrappedSpan, () => ['1']);

        // expect against the new assertion, the property will be called before the test render
        r.expect(counterAssertion);

        // once the assertion is complete, check that the stub property was called
        assert.isTrue(onClickStub.calledOnce);
    });
});

Arguments for the function can be passed after the function name, for example r.property(WrappedButton, 'onclick', { target: { value: 'value' }}). When there are multiple parameters for the function they are passed one after the other r.property(WrappedButton, 'onclick', 'first-arg', 'second-arg', 'third-arg')

Asserting Functional Children

To assert the output from functional children the test renderer needs to understand how to resolve the child render functions. This includes passing in any expected injected values.

The test renderer renderer.child() function enables children to get resolved in order to include them in the assertion. Using the .child() function requires the widget with functional children to be wrapped when included in the assertion, and the wrapped node gets passed to the .child function.

src/MyWidget.tsx

import { create, tsx } from '@dojo/framework/core/vdom';
import { RenderResult } from '@dojo/framework/core/interfaces';

import MyWidgetWithChildren from './MyWidgetWithChildren';

const factory = create().children<(value: string) => RenderResult>();

export const MyWidget = factory(function MyWidget() {
    return (
        <div>
            <h1>Header</h1>
            <MyWidgetWithChildren>{(value) => <div>{value}</div>}</MyWidgetWithChildren>
        </div>
    );
});

src/MyWidget.spec.tsx

const { describe, it } = intern.getInterface('bdd');
import { tsx } from '@dojo/framework/core/vdom';
import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';

import MyWidgetWithChildren from './MyWidgetWithChildren';
import MyWidget from './MyWidget';

// Create a wrapped node for the widget with functional children
const WrappedMyWidgetWithChildren = wrap(MyWidgetWithChildren);

const baseAssertion = assertion(() => (
    <div>
      <h1>Header</h1>
      <WrappedMyWidgetWithChildren>{() => <div>Hello!</div>}</MyWidgetWithChildren>
    </div>
));

describe('MyWidget', () => {
    it('render', () => {
        const r = renderer(() => <MyWidget />);

        // instruct the test renderer to resolve the children
        // with the provided params
        r.child(WrappedMyWidgetWithChildren, ['Hello!']);

        r.expect(baseAssertion);
    });
});

Custom Property Comparators

There are circumstances where the exact value of a property is unknown during testing, so will require the use of a custom comparator. Custom comparators get used for any wrapped widget along with the @dojo/framework/testing/renderer#compare function in place of the usual widget or node property.

compare(comparator: (actual) => boolean)
import { assertion, wrap, compare } from '@dojo/framework/testing/renderer';

// create a wrapped node the `h1`
const WrappedHeader = wrap('h1');

const baseAssertion = assertion(() => (
    <div>
        <WrappedHeader id={compare((actual) => typeof actual === 'string')}>Header!</WrappedHeader>
    </div>
));

Ignoring Nodes during Assertion

When dealing with widgets that render multiple items, for example a list it can be desirable to be able to instruct the test renderer to ignore sections of the output. For example asserting that the first and last items are valid and then ignoring the detail of the items in-between, simply asserting that they are the expected type. To do this with the test renderer the ignore function can be used that instructs the test renderer to ignore the node, as long as it is the same type, i.e. matching tag name or matching widget factory/constructor.

import { create, tsx } from '@dojo/framework/core/vdom';
import renderer, { assertion, ignore } from '@dojo/framework/testing/renderer';

const factory = create().properties<{ items: string[] }>();

const ListWidget = create(function ListWidget({ properties }) {
    const { items } = properties();
    return (
        <div>
            <ul>{items.map((item) => <li>{item}</li>)}</ul>
        </div>
    );
});

const r = renderer(() => <ListWidget items={['a', 'b', 'c', 'd']} />);
const IgnoredItem = ignore('li');
const listAssertion = assertion(() => (
    <div>
        <ul>
            <li>a</li>
            <IgnoredItem />
            <IgnoredItem />
            <li>d</li>
        </ul>
    </div>
));
r.expect(listAssertion);

Mocking Middleware

When initializing the test renderer, mock middleware can get specified as part of the RendererOptions. The mock middleware gets defined as a tuple of the original middleware and the mock middleware implementation. Mock middleware gets created in the same way as any other middleware.

import myMiddleware from './myMiddleware';
import myMockMiddleware from './myMockMiddleware';
import renderer from '@dojo/framework/testing/renderer';

import MyWidget from './MyWidget';

describe('MyWidget', () => {
    it('renders', () => {
        const r = renderer(() => <MyWidget />, { middleware: [[myMiddleware, myMockMiddleware]] });

        h
            .expect
            /** assertion that executes the mock middleware instead of the normal middleware **/
            ();
    });
});

The test renderer automatically mocks a number of core middlewares that will get injected into any middleware that requires them:

  • invalidator
  • setProperty
  • destroy

Additionally, there are a number of mock middleware available to support widgets that use the corresponding provided Dojo middleware. See the mocking section for more information on provided mock middleware.