Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mstrauss's avatar
Level 14

Using Dusk Selectors with `type` method

Trying to assure Dusk tests are less susceptible to CSS/DOM changes by using Dusk selectors, see below from this Laravel News article. However, when I one of these selectors as the first argument in the type method, like below, a InvalidElementStateException is thrown.

$b->click('@addUser'); // Performs network request
$b->whenAvailable('@userDialog', function ($b) { // Wait
    $b->type('@name', 'Gabrielle Baker');
    $b->click('@submitButton'); // Performs network request
});

Per Dusk's GitHub repo, this makes sense per its resolveForTyping method. But since it was in the Laravel News article, just wondering if anyone else has had success using Dusk Selectors in the type method.

0 likes
1 reply
LaryAI's avatar
Level 58

In Laravel Dusk, using selectors with the type method can sometimes lead to issues like InvalidElementStateException if the element is not interactable at the time the method is called. This can happen if the element is not yet visible or enabled when the type method is executed.

To resolve this, you can ensure that the element is available and interactable before attempting to type into it. Here are a few strategies you can use:

  1. Ensure Element Visibility: Make sure the element is visible and enabled before typing. You can use the waitFor method to wait for the element to be visible.

  2. Use whenAvailable Correctly: Ensure that the whenAvailable method is correctly waiting for the dialog or element to be fully available before interacting with it.

  3. Check Element State: Before typing, you can add a check to ensure the element is in the correct state.

Here's how you can modify your code to ensure the element is ready for typing:

$b->click('@addUser'); // Performs network request
$b->whenAvailable('@userDialog', function ($b) { // Wait for the dialog to be available
    $b->waitFor('@name') // Wait for the input to be visible
      ->type('@name', 'Gabrielle Baker'); // Type into the input
    $b->click('@submitButton'); // Performs network request
});

Additional Tips:

  • Debugging: If the issue persists, consider using pause to temporarily halt execution and manually inspect the state of the DOM to ensure elements are as expected.

  • JavaScript Execution: If the element is dynamically enabled via JavaScript, ensure that any necessary scripts have completed execution before interacting with the element.

By ensuring the element is fully loaded and interactable, you should be able to use Dusk selectors with the type method without encountering the InvalidElementStateException.

Please or to participate in this conversation.