In your test many times you will need to check if a particular element exists on the page and you would want to make it your assertion point. You might need to do this when you are generating the element dynamically on a given condition.
Here is how you can do it, Laravel-Dusk provides two straight-forward method assertVisible
and assertPresent
.
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')
});
}
However you can only make use of these methods if you have a handy selectory (class or id) attached to the element that you are looking for.
What if you want to check if your element exists at a particular xPath ?
You can make sure 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);
The above code will assert if the element at particular xpath exists or not.
If you want to assert for a particular number of elements you can do this.
$this->assertEquals('3', count($browser->driver->findElements(WebDriverBy::xpath('//*[@id="home-wrapper"]'))));
Check if element does not exists
$this->assertEquals('0', count($browser->driver->findElements(WebDriverBy::xpath('//*[@id="home-wrapper"]'))));
Make sure to include the WebDriverBy class object by Facebook
use Facebook\WebDriver\WebDriverBy;
Thats about it!