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

  1. import { create, tsx } from '@dojo/framework/core/vdom';
  2. import Button from '@dojo/widgets/button';
  3. import * as css from './Action.m.css';
  4. const factory = create().properties<{ fetchItems: () => void }>();
  5. const Action = factory(function Action({ properties }) {
  6. return (
  7. <div classes={[css.root]}>
  8. <Button key="button" onClick={() => properties().fetchItems()}>
  9. Fetch
  10. </Button>
  11. </div>
  12. );
  13. });
  14. export default Action;

To test that the properties().fetchItems method is called when the button is clicked:

tests/unit/widgets/Action.tsx

  1. const { describe, it } = intern.getInterface('bdd');
  2. import { tsx } from '@dojo/framework/core/vdom';
  3. import assertionTemplate from '@dojo/framework/testing/assertionTemplate';
  4. import harness from '@dojo/framework/testing/harness';
  5. import Action from '../../../src/widgets/Action';
  6. import * as css from '../../../src/widgets/Action.m.css';
  7. import Button from '@dojo/widgets/button';
  8. import { stub } from 'sinon';
  9. import { assert } from 'chai';
  10. describe('Action', () => {
  11. const fetchItems = stub();
  12. it('can fetch data on button click', () => {
  13. const h = harness(() => <Action fetchItems={fetchItems} />);
  14. h.expect(() => (
  15. <div classes={[css.root]}>
  16. <Button key="button" onClick={() => {}}>
  17. Fetch
  18. </Button>
  19. </div>
  20. ));
  21. h.trigger('@button', 'onClick');
  22. assert.isTrue(fetchItems.calledOnce);
  23. });
  24. });

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.