8

In the below code, I want to check if the element is present at XPath, then only it should execute code.

if($browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div[2]/div/table/tbody/tr['.$i.']/td[2]'))!==null) 
{ 
    $sort=$browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div22]/div/table/tbody/tr['.$i.']/td[2]'))->gettext();
echo $sort; 
}

Or else please suggest if there is another way to check element is present in laravel dusk. P.S. I tried whenAvailable method but it couldn't help me in this case.

Rushi
  • 81
  • 1
  • 1
  • 5

4 Answers4

9

Found another better and workable solution:

if ($browser->element('#IDString')) {
}
Mark Khor
  • 396
  • 5
  • 7
2

Laravel-Dusk provides two straight-forward method assertVisible (5.4+) and assertPresent (5.6+).

  • assertVisible makes sure the element is in the visible view-port of the web-page.
  • assertPresent makes sure the element exists in the source code of the page.

You can pass in any html selector to check if the element if visible.

/** @test */
public function assert_that_home_page_opens_up(){
    $this->browse(function ($browser) {
        $browser->visit('/')
            ->assertPresent('#my-wrapper')
            ->assertVisible('.my-class-element')
    });
}

xpath

The above methods can only be used if you have a selector (class or id) for the element that you are looking for.

If you need to check if an element exists at a particular xPath, you can make use of driver instance on $browser object, to directly call the methods provided by Facebook Web-driver API:

$this->assertTrue(
    count(
      $browser->driver->findElements(WebDriverBy::xpath('//*[@id="home-wrapper"]'))
     ) > 0);

Source : https://www.5balloons.info/how-to-check-if-element-is-present-on-page-using-laravel-dusk/

Daryn
  • 4,791
  • 4
  • 39
  • 52
Tushar
  • 1,166
  • 4
  • 14
  • 31
1
/*
* check element exist
* if it doesn't not exist
* will throw exception
*
* @retuen void
*/

try {
    $this->browse(function (Browser $browser) {
        $elementExist = $this->assertNotNull($browser->element('#idString'));

        if (empty($elementExist)) {
            \Log::info('element exist') 
        }
    }
} 
catch (\Exception $e) {
    \Log::info($e->getMessage());
}
Furqan Freed
  • 366
  • 1
  • 3
  • 9
0

When I want to check to see if an element exists, I usually do something like this:

$this->browse(function (Browser $browser) {
    $this->assertNotNull($browser->element('#idString'));
}
Brian Johnson
  • 117
  • 1
  • 3