Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/Api/Concerns/MakesElementAssertions.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,50 @@
*/
trait MakesElementAssertions
{
/**
* Assert that the given element is focused.
*/
public function assertFocused(string $selector): Webpage
{
$selector = $this->guessLocator($selector)->selector();

$escapedSelector = json_encode($selector);

$isFocused = $this->page->evaluate("
() => {
const element = document.querySelector({$escapedSelector});
const focusedElement = document.activeElement;
return element && focusedElement ? element === focusedElement : false;
}
");

expect($isFocused)->toBeTrue("Expected element [{$selector}] to be focused on the page [{$this->initialUrl}], but it was not.");

return $this;
}

/**
* Assert that the given element is not focused.
*/
public function assertNotFocused(string $selector): Webpage
{
$selector = $this->guessLocator($selector)->selector();

$escapedSelector = json_encode($selector);

$isNotFocused = $this->page->evaluate("
() => {
const element = document.querySelector({$escapedSelector});
const focusedElement = document.activeElement;
return element && focusedElement ? element !== focusedElement : true;
}
");

expect($isNotFocused)->toBeTrue("Expected element [{$selector}] not to be focused on the page [{$this->initialUrl}], but it was.");

return $this;
}

/**
* Assert that the page title matches the given text.
*/
Expand Down
17 changes: 17 additions & 0 deletions tests/Browser/Webpage/AssertFocusedTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

it('assert an element is focused', function (): void {
Route::get('/', fn (): string => <<<'HTML'
<div>
<input type="text" name="firstname" id="firstname" data-test="firstname" autofocus />
<input type="text" name="lastname" id="lastname" data-text="lastname" />
</div>
HTML);

$page = visit('/');

$page->assertFocused('@firstname');
$page->assertNotFocused('@lastname');
});