talhagffr
talhagffr

Reputation: 3

how can we access and get props that are passed to a component (wrapper.props().propname) always return undefined

I am testing a list component with enzyme i want to test if my component renders a list with same data that is passed to component in props

import React from 'react';
import { shallow, mount } from 'enzyme';
import renderer from 'react-test-renderer';
import { MemoryRouter } from 'react-router';

import ListComponent from '.';

const listOfLinks = [
    { url: '/one', text: 'Link one', internal: false },
    { url: '/two', text: 'Link two', internal: false },
    { url: '/datasets', text: 'Datasets', internal: true }
];

const itemsToDisplay = 4;

const props = {
    listOfLinks, itemsToDisplay
};

describe('list-Component', () => {
    it('Check if rendered list size is same as passed', () => {
        const wrapper = mount(<MemoryRouter><ListComponent {...props} /></MemoryRouter>);
        expect(wrapper.props().listOfLinks.length).toEqual(3);
    });
});

but i get expected 3 recieved : undefined

Upvotes: 0

Views: 198

Answers (1)

Will Jenkins
Will Jenkins

Reputation: 9787

Your wrapper here is a MemoryRouter, not a ListComponent. The MemoryRouter has no props.

If you want to check the props passed to ListComponent, you could do it like this:

wrapper.find(ListComponent).props() 

However, as an aside... what would you be testing if you did that? In this case, it would be that your test was providing the expected props correctly, but nothing about the component itself. Checking props like this is checking an implementation detail, when what you should be interested in is the rendered output. Better to find the actual links themselves in the wrapper and then count them.

eta: If the component was updated to take different props (but with the same rendered result) then your test would fail, even though the app is still working as required. If you check the rendered output then you are free to refactor and update and your tests will only fail when the important stuff fails - i.e. there are an incorrect number of links showing. Kent C Dodds writes a lot about this sort of stuff - check out his React Testing Library

Upvotes: 2

Related Questions