Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull requests adds a
waitForEvent()
method to theWaitsForElements
trait, making it available to theBrowser
class.It also adds a corresponding test case to
WaitsForElementsTest
.Explanation
The
waitForEvent()
method pauses the test execution until a given eventtype
occurs on atarget
element or object.This is especially useful when working with front-end libraries like InertiaJS or Hotwire/Turbo, since those libraries will trigger events that can be very helpful for automated testing. For example, clicking a link and waiting for the
inertia:navigate
event before continuing with the test.Usage examples
Waiting for events on DOM elements:
Waiting for events on
document
orwindow
:Waiting for InertiaJS events:
Waiting for events with a custom timeout in seconds:
Discussion
I’m very open to suggestions on how to improve this. A few thoughts:
I’m not huge fan of the
$target
argument being either a selector or'document'
/'window'
, since it’s not very clearly communicated. Adding a description for$target
in the docblock could help, but that would be inconsistent with the rest of the Dusk codebase.I also thought about adding different methods for differentiation:
But in the end I opted for a single method, since I felt it still had the best developer ergonomics.
—
I see potential for more convenience methods using events, for example:
visitAndWaitForEvent()
visitRouteAndWaitForEvent()
clickLinkAndWaitForEvent()
pressAndWaitForEvent()
Should these methods be desirable in the future, maybe a dedicated
WaitsForEvents
orInteractsWithEvents
trait would be good.—
Finally I’m unsure about using
eval()
in theexecuteAsyncScript()
call. But I like that it makes the JavaScript code very concise since it works with object names (document
/window
) and element references at the same time. Also in a testing environment, I feeleval()
is not that dramatic. Maybe it could lead to problems with content security policies, I’m not sure how Dusk/WebDriver handles those.