How should I test that every React component has been passed a given prop?

162 views Asked by At

I am currently using Mocha and Enzyme for testing as well as chai and chai-enzyme for assertions.

I have a presentational component called LayerList that renders multiple Layer components as child components.

I wish to pass action creators to all of the Layer items as props.

How should I write a unit test to ensure that an action creator is passed to every Layer components as a prop.

Here is my component.

LayerList.jsx

import React from 'react'
import { Component, PropTypes } from 'react';
import Layer from './Layer'
import LayerBorder from './LayerBorder'

const mapLayers = (layers, props) => 
 layers.map((layerName, i) => (
        <LayerBorder>
          <Layer layerActions={props}/>
          {i}
        </LayerBorder>
        )
    )

const LayerList = ({ layers, layerActions }) => {
    return (
        <div>
          {mapLayers(layers, layerActions)}
        </div>
        )
}

LayerList.PropTypes = {
    layers: PropTypes.arrayOf(PropTypes.string).isRequired,
    layerActions: PropTypes.shape({
        addLayer: PropTypes.func,
        removeLayer: PropTypes.func,
        toggleDragLayer: PropTypes.func,
        moveLayerIndex: PropTypes.func,
        updateLayerColour: PropTypes.func,
        toggleLayerVisibility: PropTypes.func
    }).isRequired
}

export default LayerList

Here is my (failed) attempt at the test:

 describe('should pass layer action creators as a prop to Layer components', () => {

    it('should pass addLayer', () => {  
        const wrapper = shallow(<LayerList 
                                       layers={layers} 
                                       layerActions={LayerActions} />);    


        expect(wrapper.find(Layer)
            .everyWhere(n => n.props() === 'function'}))
            .to.equal(true);

    });
1

There are 1 answers

0
therewillbecode On BEST ANSWER

I have found the solution to testing for a given prop in every child component is to change the syntax to as follows:

it('should pass a prop to every child component', () => {  

 expect(wrapper.find(Layer)
                .everyWhere(n => n.prop(/* insert prop name /*)))
                .to.equal(true);
});