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
Answer
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
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?