Objective

This recipe demonstrates one technique of:

  1. Testing functionality in your widgets
  2. Mocking imports which your widget relies upon

Note: This recipe demonstrates a vanilla approach of testing. It does not leverage the built-in testing ecosystem offered by Dojo 2 out of the box.

Procedure

  1. Create your widget:
const { w } = require('@dojo/widget-core/d');
const { WidgetBase } = require('@dojo/widget-core/WidgetBase');
const MyCustomWidget = require('./MyCustomWidget');

class HelloWorld extends WidgetBase {
    render() {
        return w(MyCustomWidget, {
            onclick: () => {
                this.invalidate();
            }
        });
    }
}

module.exports = HelloWorld;
  1. Import the dependencies for your test. This is the start of a new test file which has only one external dependency: proxyquire. The proxyquire module intercepts all of your module imports in a file, proxyquire then offers an API to mock each of these imports for the purpose of test isolation.
const assert = require('assert');
const proxyquire = require('proxyquire').noCallThru();
  1. Provide the stubs:
let invalidateCalled = false;

const stubs = {
    '@dojo/widget-core/d': {
        w(...args) {
            return args;
        }
    },
    '@dojo/widget-core/WidgetBase': {
        WidgetBase: class {
            invalidate() {
                invalidateCalled = true;
            }
        }
    },
    './MyCustomWidget'() {}
};

These stubs are used in place of the actual imports. The stubs are key/value pairs:

  1. Within your test file, require your widget through the proxyquire API and pass in the necessary stubs as defined in step 3:
const HelloWorld = proxyquire('./HelloWorld', stubs);
  1. Invoke the necessary methods on your widget so you can make assertions:
const widget = new HelloWorld();
const render = widget.render();

assert.equal(invalidateCalled, false);
render[1].onclick();
assert.equal(invalidateCalled, true);

Additional resources

Intern is a feature rich testing framework which is bundled with Dojo 2 apps by default.