如何在Jest和Enzyme中检测React Native按钮文本?
Let's work through this test issue step by step. The main problems with your original code are a syntax error and a potential mismatch in how your BorderlessButton handles text content.
First: Fix the Syntax Error
Your code has a mistake in how you're accessing the component props. props is a method (assuming you're using Enzyme for testing), not a direct property. You need to call it with parentheses to get the props object, and your chaining was missing a closing parenthesis before .toEqual().
Original broken line:
expect(wrapper.find(BorderlessButton).props.text.toEqual('D'));
Corrected version (if your button uses a text prop):
expect(wrapper.find(BorderlessButton).props().text).toEqual('D');
Second: Check How Your Button Renders Text
Many React Native button components (including some implementations of BorderlessButton) render text as children instead of using a dedicated text prop. If that's the case with your component, you'll need to check the children instead of the text prop.
Here are two reliable ways to test that:
- Check the direct children text:
expect(wrapper.find(BorderlessButton).children().text()).toEqual('D');
- Access the
childrenprop directly:
expect(wrapper.find(BorderlessButton).prop('children')).toEqual('D');
Full Working Test Example
Putting it all together, here's a robust test that covers both possibilities (adjust based on your actual component implementation):
it('should render a <BorderlessButton /> with correct text', () => { // Verify the button exists expect(wrapper.find(BorderlessButton)).toHaveLength(1); // Use this if your button uses a "text" prop expect(wrapper.find(BorderlessButton).props().text).toEqual('D'); // OR use this if your button renders text as children expect(wrapper.find(BorderlessButton).children().text()).toEqual('D'); });
The key here is to match your test to how your BorderlessButton component actually receives and renders the text. If you're unsure, check the component's source code to see whether it accepts a text prop or uses children for the label.
内容的提问来源于stack exchange,提问作者Shashika Virajh

