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:
React 16.2.0
Jest 21.2.1
React-test-renderer: 16.2.0
To render multiple JSX elements in React, you can loop through an array with the . map() method and return a single element. In the next example, you will examine why you would want to add a unique key to a list of elements rendered by an array.
Step 1: You will start a new project using create-react-app so open your terminal and type. Step 2: Switch to the jest-testing folder using the following command. Step 6: Create a Button. js file and Button.
How we will render an Array of Objects? We will use the map function to access each object from the array. The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With