Authoring Plugins
Anatomy of a Plugin
Arguments
Returns
class Person { sayHello() { return 'Hello!'; } } const myPlugin = (node, options) => { const person = new Person(); return { node, options, controller: person, }; }; const mount = createMount({ p: myPlugin, }); const wrapper = mount(<MyComponent />); wrapper.p.sayHello();const myPlugin = (node, options) => { const person = new Person(); return { node, controller: person, options: { ...options, context: { ...options.context, person, }, }, }; }; const mount = createMount({ p: myPlugin }); function MyComponent(props, context) { return <button onClick={() => context.person.sayHello()}>Say Hello</button>; } MyComponent.childContextTypes = { person: PropTypes.instanceOf(Person) }; const wrapper = mount(<MyComponent />); wrapper.find('button').simulate('click');const postMessagePlugin = (node, options) => { return { node, controller: null, options: { ...options, context: { ...options.context, messages: [], }, }, updater: wrapper => { const listener = event => { wrapper.setContext({ messages: wrapper.context('messages').concat([event.data]), }); }; // listen for message events and update the enzyme wrapper when they are // received. window.addEventListener('message', listener, false); // Return a function that will get called when the component is unmounted. return () => { // Clean up the listener on unmount to avoid a memory leak! window.removeEventListener('message', listener, false); }; }, }; };
Best Practice: Export a Factory
Authoring Utilities
Last updated
Was this helpful?