CherryNerd
CherryNerd

Reputation: 1314

How do I test an array of JSX elements in jest with react renderer

I'm using React 16.2 and would like to test on of my components functionality.
When calling one of the functions, it returns an array of elements with Buttons, which have an onClick props that I'd like to test.

The problem is, I can only find the first element in the array.

The code is as followed:

Comp.js

class Comp extends Component {

    renderButtons = () => {
        const list = [];

        list.push(<Button key="first" onClick={() => console.log('foo')}/>);
        list.push(<Button key="second" onClick={() => console.log('bar')}/>);
        list.push(<Button key="third" onClick={() => console.log('baz')}/>);

        return list;
    }

    render() {
        return (
            <div>Empty div</div>
        )
    }
}

Comp.test.js

test('.renderButtons', () => {
    const comp = new Comp();
    const component = renderer.create(comp.renderButtons());

    const root = components.root;

    // Using root.findByProps({key: 'second'}); throws an error
});

Tech stack:

Upvotes: 11

Views: 9328

Answers (1)

Brian Adams
Brian Adams

Reputation: 45830

This is an older question but it seems to get a lot of views so I'll add an answer.

The "key" prop (along with the "ref" prop) is a reserved React prop that will throw an error if accessed. Any other prop can be used in the findByProps function. Additional functions, such as findAllByType, are available on the Test Instance.

Here is an example:

const SimpleComponent = ({text}) => (<div>{text}</div>);

const ListComponent = () => {
  const list = [];
  list.push(<SimpleComponent key="first" text="the first one" />);
  list.push(<SimpleComponent key="second" text="the second one" />);
  list.push(<SimpleComponent key="third" text="the third one"/>);
  return list;
}

test('ListComponent renders correctly', () => {
  const component = renderer.create(<ListComponent/>);

  const list = component.root.findAllByType(SimpleComponent);
  expect(list.length).toBe(3);
  expect(list[1].props.text).toBe('the second one');

  const third = component.root.findByProps({text: 'the third one'});
  expect(third.type).toBe(SimpleComponent);
});

Upvotes: 8

Related Questions