reactjsfacebooktestingjestjsenzyme

How to get props of a component when unit testing using jestjs


I am using shallow from enzyme. I want to get the props being passed to the component -- in testing file. Like so in example but I am getting undefined.

console.log(wrapper.props()) 

It should return an object containing props but it's returning a jsx object.

Here is my code:

import React from 'react';
import {
    configure,
    shallow
} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import MenuList from './MenuList';
import {
    Link
} from 'react-router-dom';

configure({
    adapter: new Adapter()
});

const footerItem = {
    label: '',
    links: [{
        label: '',
        link: '/'
    }]
}

describe('<MenuList />', () => {

            let wrapper;
            beforeEach(() => {
                    wrapper = shallow( < MenuList footerItem = {
                            footerItem
                        }
                        / > );
                    });

                it('should render Link', () => {
                    console.log(wrapper.props().footerItem); // This should print footerItem object but returning  undefined
                    expect(wrapper.find(Link).length).toBeGreaterThan(0);
                });
            });

// and here is the code of menulist component/


import React from 'react';
import { Link } from 'react-router-dom';

const menuList = (props) => {
    let linkArray=[];
        linkArray = props.footerItem.links.map((item,index)=>{
            return <li key={index}>
                    <Link to={item.link}>
                        {item.label}
                    </Link></li>
        })

   return (
        <div className="footer-link">
            <h6>{props.footerItem.label}</h6>
                <ul>
                    {linkArray}
                </ul>
        </div>
   )
}
export default menuList;


Solution

  • const wrapper = mount(<MyComponent foo={10} />);
    expect(wrapper.props().children).to.equal(10);
    

    EDIT:

    And like @Must keem pointed out, this works also:

    const wrapper = mount(<MyComponent foo={10} />);
    expect(wrapper.instance().props.foo).to.equal(10);