Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nezarfadle/911d110e6d8cdd3f1ea2aab2d8beb08b to your computer and use it in GitHub Desktop.
Save nezarfadle/911d110e6d8cdd3f1ea2aab2d8beb08b to your computer and use it in GitHub Desktop.

This code snippet overrides php DuskTestCase->createBrowsers method to extends the functionality and add the elements count assertion

File tests/Browser/BaseBrowser.php

// Extend Browser Class
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;
  }

}

File: tests/DuskTestCase.php

// Overriding DuskTestCase createBrowsersFor method to pass our BaseBrowser class instead of the Browser class

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 ( index.blade.php )

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

File: tests/Browser/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');

        });
    }
}

Run the test

php artisan dusk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment