diff --git a/README.md b/README.md index 70fca7a..85cca99 100644 --- a/README.md +++ b/README.md @@ -82,5 +82,10 @@ You can pass a `className` like `test-class.test-class--modified` to find a comp Find only one instance of a component in the tree with a ref that matches `ref`. ```javascript -ReactComponent findWithRef(ReactComponent tree, string ref) +ReactComponent|ReactComponent[] findWithRef(ReactComponent tree, string ref [, string ref...]) +``` +#### Usage +``` +const header = ShallowTestUtils.findWithRef(component, 'head') +const [list, close] = ShallowTestUtils.findWithRef(component, 'list', 'close-button') ``` diff --git a/specs/find-with-ref-spec.js b/specs/find-with-ref-spec.js index 81c5f04..6a6db23 100644 --- a/specs/find-with-ref-spec.js +++ b/specs/find-with-ref-spec.js @@ -46,4 +46,14 @@ describe('`findWithRef`', function() { expect(() => findWithRef(this.tree, 'non-existing')).toThrow(); }); + it('should find multiple refs', function() { + expect(findWithRef(this.tree, 'input-ref', 'other-component-ref').length).toBe(2); + expect(findWithRef(this.tree, 'input-ref', 'other-component-ref')[0].props.className).toBe('input-ref-class'); + expect(findWithRef(this.tree, 'input-ref', 'other-component-ref')[1].props.test).toBe('test'); + }); + + it('should not find anything if one of the multiple refs in not found', function() { + expect(() => findWithRef(this.tree, 'input-ref', 'non-existing')).toThrow(); + }); + }); diff --git a/src/find-with-ref.js b/src/find-with-ref.js index e03cf12..c4c0d65 100644 --- a/src/find-with-ref.js +++ b/src/find-with-ref.js @@ -5,11 +5,11 @@ import findAll from './find-all'; * Finds component in the tree with a ref that matches * `ref`. * - * @param {ReactComponent} tree the rendered tree to traverse - * @param {String} ref to find - * @return {ReactComponent} found component + * @param {ReactComponent} tree the rendered tree to traverse + * @param {...String} ref the ref(s) to find + * @return {ReactComponent|ReactComponent[]} found component or an array of it */ -export default function findWithRef(tree, ref) { +function findWithRefForOne(tree, ref) { const found = findAll(tree, component => { if (React.isValidElement(component)) { return component.ref != null && component.ref === ref; @@ -24,3 +24,10 @@ export default function findWithRef(tree, ref) { return found[0]; } + +export default function findWithRef(root, ...refs) { + if(refs.length == 1) + return findWithRefForOne(root, refs[0]); + + return refs.map(ref => findWithRefForOne(root, ref)); +}