Oct 10, 2017
0
Level 17
Fixing date input in Dusk
Laravel Dusk cannot fill date inputs, due to a long-standing bug in ChromeDriver. This is how I fixed it.
Start by extending the Dusk Browser object, so we have a place to add custom methods. In tests/DuskTestCase.php:
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication
// Custom browser class. Allows for extending Dusk behaviour
protected function newBrowser($driver)
{
return new DuskBrowser($driver);
}
//... standard DuskTestCase code here ...
}
Now make that new class tests/DuskBrowser.php:
<?php
namespace Tests;
use Carbon\Carbon;
use Laravel\Dusk\Browser;
class DuskBrowser extends Browser
{
public function fillDate($selector, Carbon $date)
{
$dateString = $this->generateDateString($date);
return $this->keys($selector, $dateString);
}
// ChromeDriver cannot cope with date inputs, so must remove the hyphens.
// Also note that browser date format is locale-specific! We are using UK DD-MM-YYYY
private function generateDateString(Carbon $date)
{
$date = $date->toDateString();
$date = explode('-', $date);
$date = array_reverse($date);
return implode($date, '');
}
}
You will need to adjust the generateDateString() logic slightly if your browser is set to US locale. Now use the new method in your tests:
use Laravel\Dusk\Browser; // This can stay the same!
class SomeDuskTest extends DuskTestCase
{
public function testDate()
{
$this->browse(function (Browser $browser) {
$browser->visit('/some-form')
->fillDate('input[name=date]', Carbon::now()->addDays(5));
});
}
}
Please or to participate in this conversation.