Mocking
A common type of test is validating a widget’s user interface renders as expected without necessarily being concerned with the widget’s underlying business logic. These tests may want to assert scenarios such as button clicks calling widget property methods, without concern as to what the property method implementations are, only that the interface is called as expected. A mocking library such as Sinon can be used to help in these cases.
src/widgets/Action.tsx
import { create, tsx } from '@dojo/framework/core/vdom';
import Button from '@dojo/widgets/button';
import * as css from './Action.m.css';
const factory = create().properties<{ fetchItems: () => void }>();
const Action = factory(function Action({ properties }) {
return (
<div classes={[css.root]}>
<Button key="button" onClick={() => properties().fetchItems()}>
Fetch
</Button>
</div>
);
});
export default Action;
To test that the properties().fetchItems
method is called when the button is clicked:
tests/unit/widgets/Action.tsx
const { describe, it } = intern.getInterface('bdd');
import { tsx } from '@dojo/framework/core/vdom';
import assertionTemplate from '@dojo/framework/testing/assertionTemplate';
import harness from '@dojo/framework/testing/harness';
import Action from '../../../src/widgets/Action';
import * as css from '../../../src/widgets/Action.m.css';
import Button from '@dojo/widgets/button';
import { stub } from 'sinon';
import { assert } from 'chai';
describe('Action', () => {
const fetchItems = stub();
it('can fetch data on button click', () => {
const h = harness(() => <Action fetchItems={fetchItems} />);
h.expect(() => (
<div classes={[css.root]}>
<Button key="button" onClick={() => {}}>
Fetch
</Button>
</div>
));
h.trigger('@button', 'onClick');
assert.isTrue(fetchItems.calledOnce);
});
});
In this case, a mock of the fetchItems
method is provided to the Action widget that requires items to be fetched. The @button
key is then targeted to trigger the button’s onClick
, after which an assertion is validated that the fetchItems
mock was called only once.
See the Sinon documentation for more details on mocking.