如何测试无状态组件?Jest和Enzyme测试React函数组件遇报错
Hey there! Let’s figure out why your Jest/Enzyme test for the InfoToolTip component is failing, even though the component works fine in your app. From the code snippet you shared, I can spot a few common pitfalls that might be causing the issue—let’s break them down one by one:
1. You’re Handling Props Non-Standardly (and Maybe Incorrectly in Tests)
Looking at your component definition:
export const InfoToolTip = data => { const { informations = [] } = data.data; // ... rest of your code }
React components receive a single props object as their first argument, not a data prop directly. Right now, your component assumes the entire props object is the data value passed from the parent. That might work in your app if you’re spreading the data like <InfoToolTip {...dataObj} />, but it’s not standard, and it’s easy to mess up in tests.
First, let’s fix the component to follow React conventions—it’ll make testing way easier:
// Updated component definition export const InfoToolTip = (props) => { // Fallback to empty object if data isn't passed const { data = {} } = props; // Fallback to empty array if informations is missing const { informations = [] } = data; const listOfInfo = () => { return informations.map((info, index) => { const { name, id } = info; return ( <li key={id}> {/* Don't forget the key! More on that next */} <a href={`/details/${id}`}>{name}</a> </li> ); }); }; return <ul>{listOfInfo()}</ul>; };
Then, in your test, pass props correctly:
// Mock your test data const mockProps = { data: { informations: [ { id: 1, name: "User Privacy Policy" }, { id: 2, name: "Terms of Service" } ] } }; // Render the component with the mock props const wrapper = shallow(<InfoToolTip {...mockProps} />);
2. Missing Key Prop in List Items
Your map function returns <li> elements without a key prop. React requires keys for list items to optimize re-renders, and while your app might run without obvious issues, Jest/Enzyme can flag this (or it might cause flaky tests). Always add a unique key—use the id if it’s unique, or index as a last resort:
<li key={info.id}> {/* Add this line */} <a href={`/info/${info.id}`}>{info.name}</a> </li>
3. Shallow Rendering Might Be Hiding Issues
If you’re using shallow() in your test, it only renders the component itself—not any nested components (like the <a> tag if it has custom logic). If your test is checking something related to the link, try using mount() instead for a full render:
import { mount } from 'enzyme'; // Use mount instead of shallow const wrapper = mount(<InfoToolTip {...mockProps} />);
Just make sure your Jest setup includes jsdom (most modern setups do) to simulate the DOM.
4. Your Test Assertions Don’t Match the Component Output
Double-check your test assertions to make sure they’re targeting the right elements. For example:
- To count the number of list items:
expect(wrapper.find('li')).toHaveLength(mockProps.data.informations.length); - To check the text of the first link:
expect(wrapper.find('a').at(0).text()).toBe("User Privacy Policy");
If your selectors are wrong or you’re expecting values that don’t match your mock data, the test will fail.
5. No Fallback for Undefined data Prop
If your test doesn’t pass the data prop at all, your original component would throw an error when trying to access data.data. The updated component above fixes this with const { data = {} } = props, so even if data is missing, it won’t crash.
If none of these fix the issue, share the exact error message from Jest and your full test code—I can help you narrow it down further!
内容的提问来源于stack exchange,提问作者Mukesh

