...

/

Working With and Testing Using Component's Props

Working With and Testing Using Component's Props

Learn how to test the React Component's props to test the components using the Enzyme's methods related to props.

We'll cover the following...

Working with props

Currently, CarouselButton renders an empty <button> element, which isn’t very useful. We need to add support for setting the children of the <button> element, which will be the text that the user sees. Add a test for that to the existing describe() block:

Press + to interact
// src/tests/CarouselButton.test.js
...
it('passes `children` through to the <button>', () => {
const text = 'Button text';
const wrapper = shallow(<CarouselButton>{text}</CarouselButton>);
expect(wrapper.prop('children')).toBe(text);
});
...

The wrapper.prop(propName) method returns the value of the prop with the given name. Remember that wrapper, in this case, represents the <button> rendered by CarouselButton. Currently, that button is rendered without children. Thus, failing the test. To fix that, add some prop-passing logic to the component:

Press + to interact
// src/CarouselButton.js
...
const CarouselButton = ({ children }) => <button>{children}</button>;
...

When a component is defined as a function, that function receives the component instance’s props object as the first argument. The argument list ({ children }) uses ES6’s destructuring syntax to extract props.children as children, which is then passed through to the rendered <button>. Any other props are ignored.

One subtle point here is ...

Access this course and 1400+ top-rated courses and projects.