Type into a TextField
Use the TypingText() method to simulate typing text into a text field in your tests. This method sends the appropriate keyboard events to the target element, mimicking a real user interaction.
Example
The following examples show how to simulate typing text into a text field:
[Test]
public void TypingTextExample()
{
// Make sure the UI is totally up to date.
simulate.FrameUpdate();
// Fetch and focus the textField's textElement.
var textField = rootVisualElement.Q<TextField>("MyTextField");
var textElement = textField.Q<TextElement>();
Assume.That(textField, Is.Not.Null);
textField.Focus();
Assume.That(textField.text, Is.Empty);
Assume.That(textField.hasFocusPseudoState, Is.True);
// Type into the textField.
var typedText = "Typed text.";
simulate.TypingText(typedText);
simulate.FrameUpdate();
Assert.That(textField.text, Is.EqualTo(typedText));
}
Platform differences at runtime
When running tests in Play mode or in a runtime assembly, the behavior of the TypingText() method can vary based on the platform due to its different requirements and behaviors at runtime.
The following table summarizes the differences:
| Platform | Events sent | Requirements |
|---|---|---|
| Windows, Mac, Linux, WebGL | UI Toolkit events | You must focus on the TextElement. |
| XboxOne, PS5, PS4, Android, iPhone, tvOS | Directly on TouchScreenKeyboard |
You must focus on the TextElement to summon the TouchScreenKeyboard. |
| Nintendo Switch | Unsupported | N/A |