This code snippet overrides DuskTestCase->createBrowsers method to allow HTML elements count assertion
// Extend Browser Class
// File BaseBrowser.php
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use PHPUnit_Framework_Assert as PHPUnit;
class BaseBrowser extends Browser
{
public function assertElementsCountIs( $count, $selector )
{
PHPUnit::assertEquals( $count, count($this->elements( $selector )));
return $this;
}
}
// Overriding DuskTestCase createBrowsersFor method to pass the BaseBrowser class instead of Browser class
// File: DuskTestCase.php
namespace Tests;
use Tests\Browser\BaseBrowser;
use Laravel\Dusk\TestCase as BaseTestCase;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Prepare for Dusk test execution.
*
* @beforeClass
* @return void
*/
public static function prepare()
{
static::startChromeDriver();
}
/**
* Create the RemoteWebDriver instance.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()
);
}
/**
* Create the browser instances needed for the given callback.
*
* @param \Closure $callback
* @return array
*/
protected function createBrowsersFor(\Closure $callback)
{
if (count(static::$browsers) === 0) {
static::$browsers = collect([new BaseBrowser($this->createWebDriver())]);
}
$additional = $this->browsersNeededFor($callback) - 1;
for ($i = 0; $i < $additional; $i++) {
static::$browsers->push(new BaseBrowser($this->createWebDriver()));
}
return static::$browsers;
}
}
/**
* How to use
* assuming that we have a ( ul element ) in our view
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
*/
// File: HtmlElementsCountTest.php
namespace Tests\Browser\Twitter;
use Tests\DuskTestCase;
class HtmlElementsCountTest extends DuskTestCase
{
public function test_ul_li_count()
{
$this->browse(function ($browser) {
$browser->visit('page')
->assertElementsCountIs( 3, 'ul li');
});
}
}