Skip to content

Commit

Permalink
Add waitForEvent() method (#972)
Browse files Browse the repository at this point in the history
* Add waitForEvent

This commit adds a `waitForEvent()` method to the `WaitsForElements`
trait, making it available to the `Browser` class.

The `waitForEvent()` method pauses the test execution until a given
event `type` occurs on a `target` element or object.

It also adds a corresponding test case to `WaitsForElementsTest`.

* Fix syntax in exception message

* formatting

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
michaelhue and taylorotwell authored Apr 11, 2022
1 parent ea9a455 commit 98901d4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/Concerns/WaitsForElements.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Closure;
use Exception;
use Facebook\WebDriver\Exception\NoSuchElementException;
use Facebook\WebDriver\Exception\ScriptTimeoutException;
use Facebook\WebDriver\Exception\TimeOutException;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Illuminate\Support\Arr;
Expand Down Expand Up @@ -343,6 +344,38 @@ public function clickAndWaitForReload($selector = null)
});
}

/**
* Wait for the given event type to occur on a target.
*
* @param string $type
* @param string|null $target
* @param int|null $seconds
* @return $this
*
* @throws \Facebook\WebDriver\Exception\TimeOutException
*/
public function waitForEvent($type, $target = null, $seconds = null)
{
$seconds = is_null($seconds) ? static::$waitSeconds : $seconds;

if ($target !== 'document' && $target !== 'window') {
$target = $this->resolver->findOrFail($target ?? '');
}

$this->driver->manage()->timeouts()->setScriptTimeout($seconds);

try {
$this->driver->executeAsyncScript(
'eval(arguments[0]).addEventListener(arguments[1], () => arguments[2](), { once: true });',
[$target, $type]
);
} catch (ScriptTimeoutException $e) {
throw new TimeoutException("Waited {$seconds} seconds for event [{$type}].");
}

return $this;
}

/**
* Wait for the given callback to be true.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/WaitsForElementsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,4 +324,23 @@ public function test_wait_for_reload()

$browser->waitForReload();
}

public function test_wait_for_event()
{
$driver = m::mock(stdClass::class);
$driver->shouldReceive('manage->timeouts->setScriptTimeout')->with(3);
$driver->shouldReceive('executeAsyncScript')->with(
'eval(arguments[0]).addEventListener(arguments[1], () => arguments[2](), { once: true });',
['body form', 'submit']
);

$resolver = m::mock(stdClass::class);
$resolver->shouldReceive('findOrFail')
->with('form')
->andReturn('body form');

$browser = new Browser($driver, $resolver);

$browser->waitForEvent('submit', 'form', 3);
}
}

0 comments on commit 98901d4

Please sign in to comment.