TestCafe中调用pressKey('tab')后,如何定位焦点元素使用typeText?
Great question! Let's walk through how to solve this step by step.
First: What to put in the ??? spot
The most reliable way to target the email input (the one you tab into) is to use its own unique attributes—just like you did for the city, street, and telephone fields. Here are your best options:
- Use the input's native attributes: If the email field has a
titleattribute (like the others), use that:Selector('[title|="Email"]') - Use a specific class or ID: If it has a unique class (e.g.,
validate-email) or ID (e.g.,email), those work even better:Selector('#email') // If it has an ID // OR Selector('.input-text.validate-email.required-entry') // Using its validation classes - Fallback: DOM order (less recommended): If you can't find unique attributes, you can target it relative to the zip input. For example, if it's the immediate next input sibling:
Note: This is fragile—if the page structure changes, your test will break. Stick to unique attributes whenever possible.Selector('.input-text.validate-zip-international.required-entry').nextSibling('input')
Second: Can pressKey('tab') return the target selector?
Short answer: No. TestCafe's pressKey method returns the TestController object (the t variable) to enable method chaining, not the element you navigated to. There's no built-in way to get the focused element directly from pressKey.
Updated Test Code Example
Here's how your code should look, using a reliable attribute for the email field:
await t.typeText(Selector('[title|="City"]'),'St. Petersburg') await t.typeText(Selector('[title|="Street Address"]'),'777 The Heavenly Vulga') await t.typeText(Selector('[title|="Telephone"]'),'6085550119') await t.typeText(Selector('.input-text.validate-zip-international.required-entry'),'40475') // If you need to test tab navigation (optional—typeText auto-focuses the element) await t.pressKey('tab') // Target the email input directly await t.typeText(Selector('[title|="Email"]'), email)
A quick note: You don't actually need the pressKey('tab') call unless you're specifically testing that the tab navigation works correctly. TestCafe's typeText automatically focuses the target element before typing, so you could skip the tab step entirely if navigation testing isn't part of your requirement.
内容的提问来源于stack exchange,提问作者Vladimir_314159

