React Native测试:Enzyme simulate遇多InputBox节点报错如何解决?
Hey there! That error pops up because your wrapper.find(InputBox) is matching two instances of your InputBox component, and Enzyme's simulate() method only works on a single node at a time. No worries though—here are a few straightforward, reliable fixes you can try:
1. Target a specific InputBox by index
If you know the order of your InputBox components won’t change, use Enzyme’s .at() method to select the exact instance by its position (index starts at 0):
it('changes text', () => { // Simulate change on the first InputBox wrapper.find(InputBox).at(0).simulate('change', { target: { value: 'text Given' } }); // Or target the second InputBox with index 1 // wrapper.find(InputBox).at(1).simulate('change', { target: { value: 'text Given' } }); });
2. Use unique props to identify InputBoxes (Recommended)
The most robust approach is to add unique test-focused props like testID or name to each InputBox. This avoids breakage if component order shifts later:
First, update your component to include unique props:
// In your React Native component <InputBox testID="username-input" /> <InputBox testID="email-input" />
Then target the specific InputBox in your test:
it('changes text', () => { // Filter InputBoxes by their testID wrapper.find(InputBox).filter({ testID: 'username-input' }).simulate('change', { target: { value: 'text Given' } }); // Alternatively, query directly by testID (if the prop is passed to the underlying input) // wrapper.find('[testID="username-input"]').simulate('change', { target: { value: 'text Given' } }); });
3. Narrow down by parent component
If the two InputBoxes live inside different parent containers, first locate the parent, then find the InputBox within it:
it('changes text', () => { // Find the parent container of your target InputBox const usernameContainer = wrapper.find('.username-container'); // Select the InputBox inside that parent usernameContainer.find(InputBox).simulate('change', { target: { value: 'text Given' } }); });
Pro tip: Using testID is the best practice here—it’s explicitly designed for testing and won’t affect your app’s UI or functionality.
内容的提问来源于stack exchange,提问作者Shashika Virajh

