使用TestCafe测试react-select下拉框失效,求问题排查
Let’s break down what’s going wrong with your TestCafe test for react-select, and fix it step by step.
Key Issues in Your Code
Wrong DOM Element Assumptions
react-select doesn’t render native<option>elements—it uses a custom DOM structure with classes likecustomSelect__control(the clickable trigger to open the dropdown) andcustomSelect__option(the individual dropdown items). Trying to target<option>will never work here.Syntax & Logic Errors in
dropDownValueSelector
Your function has several critical bugs:
- You reference a
customSelectvariable that’s never defined - The chain
await t.click(customSelect).find(...)is invalid—findis a selector method, not an action you can chain off a TestCafe click - There’s an extra closing
});at the end that breaks syntax - You’re targeting
.customSelect__input, which is irrelevant here since your component hasisSearchable={false}(this element won’t exist or serve any purpose)
- Inaccurate Selector Targeting
While you pass theid="#my-dropdown"prop to react-select, you need to ensure you’re clicking the actual interactive control element that opens the dropdown—not just the root element directly (though the root might map to the control, being explicit with react-select’s class is more reliable).
Fixed Solution
Here’s the corrected dropDownValueSelector function, tailored to react-select’s actual DOM structure:
import { Selector } from 'testcafe'; export default async (t, { selector, newValue }) => { // Target the clickable control element of react-select const selectControl = Selector(selector).find('.customSelect__control'); // Click to open the dropdown menu await t.click(selectControl); // Locate the target option using react-select's custom option class const targetOption = Selector('.customSelect__option').withText(newValue); // Wait for the option to become visible (handles async rendering delays) await t.expect(targetOption.exists).ok(); // Click the option to select it await t.click(targetOption); };
Additional Checks to Ensure Success
- Verify your custom Select component correctly passes the
idprop to the underlying react-select. The react-select component should render theidon its root control element (the one withcustomSelect__controlclass), so your#my-dropdownselector will find it. - If your options load asynchronously (e.g., from an API), add an extra wait for the menu to render, or use
await t.expect(Selector('.customSelect__menu').exists).ok()before targeting the option. - Ensure
newValueexactly matches the displayed text in the option—withTextis case-sensitive by default. UsewithText(new RegExp(newValue, 'i'))if you need case-insensitive matching.
Revised Test Case
Your test case itself is structured correctly, but here it is for reference:
test('DropDown test', async t => { await dropdownValueSelector(t, { selector: '#my-dropdown', newValue: 'value 2' }); });
内容的提问来源于stack exchange,提问作者Sunny

