Welcome to the Future! ๐
Ever wanted a superhero sidekick that could click buttons, fill forms, and even take screenshots of your Laravel applicationโs UI? Look no further than Laravel Dusk - your new web-browsing, test-running, debugging pal! ๐ต๏ธโโ๏ธ
Installation ๐ฆ
Letโs get this party started! To make sure our robot friend can navigate your app effortlessly, we need to set up the right tools.
ChromeDriver: Our Secret Weapon ๐ ๏ธ
First things first - youโll want to install the ChromeDriver (donโt worry, it wonโt actually drive a car). This is our superheroโs steering wheel through your appโs user interface. You can find installation instructions for various platforms here.
Browser Variety: Because variety is the spice of life ๐ถ๏ธ
Fancy testing your app with a different browser? No problem! Laravel Dusk supports Firefox and Safari as well, not just Chrome. More on that here.
Getting Started ๐
Now that our trusty robot is equipped with a browser, itโs time to let it loose on your application!
Test Generation ๐
Generate tests using Artisan commands - think of them as blueprints for your robotโs missions. make:dusk is all you need to get started!
Database Reset ๐
For each mission, our bot will be working on a freshly baked app, just like having a new test device every time. You can reset the database after each test using various Artisan commands - check this out!
Running Tests ๐๏ธ
Once your tests are generated, itโs time to let the robot run wild! You can execute tests with a simple php artisan dusk command.
Environment Handling ๐
Different environments require different testing configurations - no worries! Laravel Dusk allows you to switch between environments easily based on your needs. More info here.
Browser Basics ๐ง
Letโs give our superhero a feel of the controls!
Creating Browsers ๐
Our robot can switch between browsers as needed. To create a new browser instance, simply use $browser = \Illuminate\Testing\Dusk\Browser::make($browserType); where $browserType is the browser you want to use (Chrome, Firefox, Safari).
Navigation ๐ซ
The robot can navigate through your application by visiting different URLs. You can make it go to a specific page with $browser->visit($url);.
Resizing Browser Windows ๐
Want the robot to have a closer look? Use $browser->resize(width, height) to adjust its browser window size.
Browser Macros ๐
Make your tests more dynamic by defining custom macros for the robot! This will help you save time and make your tests more reusable. More on that here.
Authentication ๐
Got a protected area in your app? No problem! The robot can log in as any authenticated user by using $user = App\Models\User::find(1); $browser->loginAs($user);.
Cookies ๐ช
Need to test how your app handles cookies? Laravel Dusk has got you covered! You can set and get cookies with $browser->cookies()->set('cookieName', 'cookieValue'); and $browser->cookies()->get('cookieName').
Executing JavaScript ๐ป
Want to execute custom scripts in your tests? $browser->script('// JavaScript code here'); is all you need!
Taking a Screenshot ๐ธ
Keep track of what the robot sees by taking screenshots with $browser->screenshot('path/to/save');.
Storing Console Output to Disk ๐พ
If you want to save the console output for later analysis, use $browser->dumpOutput();.
Interacting With Elements ๐ฑ๏ธ
Our robot has a keen eye and can interact with various elements on your appโs UI.
Dusk Selectors ๐ต๏ธโโ๏ธ
Find the specific element you want to interact with using Dusk selectors. These are similar to CSS selectors, but tailored for Laravel Dusk!
Text, Values, and Attributes ๐
The robot can read and write values on your appโs UI by using commands like $element->value(), $element->text(), or even target specific attributes with $element->attribute('attributeName').
Interacting With Forms โ๏ธ
Need to fill out a form? Our robot can do that! Use $form->fill([ 'field1' => 'value1', 'field2' => 'value2' ]); to fill out your form.
Attaching Files ๐
Got a file upload form in your app? No problem! The robot can attach files with $browser->attach(pathToFile);.
Pressing Buttons ๐
Want the robot to click a button? Simply use $element->click().
Clicking Links ๐
Have a link your robot needs to follow? Use $link->click(); to navigate to the linked page.
Using the Keyboard โจ๏ธ
Want the robot to type something out? You can use $element->type('text');.
Using the Mouse ๐ญ
Need more control over your mouse movements? The robot has you covered with commands like $browser->move($x, $y);.
JavaScript Dialogs ๐ฃ๏ธ
Got a modal or alert box in your app? The robot can interact with it using commands like $browser->acceptModal(); or $browser->rejectModal();.
Interacting With Inline Frames ๐ผ
Need to test how your app handles inline frames (iframes)? Laravel Dusk allows you to do that by using commands like $browser->within('#frameId', function ($child) {...});.
Scoping Selectors ๐
Want to narrow down your search for specific elements? Use the $element->find() method to scope your search!
Waiting for Elements โฑ๏ธ
The robot can wait for specific elements to appear on the screen before interacting with them. Use $browser->waitForSelector('#selector', $seconds);.
Available Assertions ๐
Making sure your app works as intended is important! Laravel Dusk provides a variety of assertions to help you test the expected outcomes. Check out the assertion documentation for more info!
Pages ๐ข
Want to organize your tests better? Create pages to represent different sections of your application and group related tests together! Learn more here.
Components ๐ฏ
Got a reusable UI element in your app? Create components to make your tests more modular and easier to maintain! More info here.
Continuous Integration ๐
Once youโve written your tests, you want to make sure they run automatically every time you make changes to your application! Laravel Dusk integrates with popular CI services such as Heroku CI, Travis CI, GitHub Actions, and Chipper CI. More on that here.
Now go forth and automate your Laravel application testing with the power of Laravel Dusk - your new web-browsing, test-running, debugging pal! ๐ต๏ธโโ๏ธ๐
Alrighty, Buckaroos! ๐ค
Attention, Pardners! ๐ฃ
Yippee-ki-yay, Pest 4! (Not to be confused with the action-packed movie) is here and itโs packing some serious performance and usability punches compared to our trusty olโ Laravel Dusk. So if youโre starting a fresh project, we reckon you should saddle up with Pest for all your browser testing needs.
Now, letโs chat about Laravel Dusk - the cowboy of the coding world who makes browser automation and testing an easy-peasy ride. Unlike most wranglers, Dusk wonโt make you install JDK or Selenium on your trusty steed (computer). No sir! Instead, Dusk relies on a lone ranger named ChromeDriver for those dusty trails of automation. But if youโve got your heart set on another Selenium-compatible driver, well, go ahead, partner!
๐ง Caution: Cowboy jargon ahead! ๐ง
Now, letโs get our horses hitched and gallop on to the installation process. (Just kidding - no actual horses are needed here.) ๐๐
Alrighty then! Letโs get this show on the road, partner. First things first: youโre gonna need a horse of a different color โ or at least Google Chrome. Pop over to https://www.google.com/chrome and grab yourself a steed. Once youโve done that, saddle up and ride into Composer territory with this command:
composer require laravel/dusk --dev
[!WARNING] Now hereโs the part where Cowboy Code 101 kicks in: if you find yourself manually roping Duskโs service provider, remember โ that rope ainโt for your production environment. Lassoing it there could result in unwanted strangers galloping through your applicationโs saloon doors.
Once the Dusk package is installed, run the dusk:install Artisan command. This here command will corral a tests/Browser directory, an example Dusk test, and round up the Chrome Driver binary for your operating system:
php artisan dusk:install
Next, youโll need to lasso the APP_URL environment variable in your applicationโs .env file. Make sure this value matches the URL youโd use to wrangle your application in a web browser.
Note
If youโre using Laravel Sail to manage your local development shindig, donโt forget to consult its documentation on configuring and running Dusk tests.
Now, wrangling ChromeDriver installations is a bit of a rodeo. Hereโs how you can ensure everyoneโs on the same page:
- First, make sure your operating system knows where to find its trusty steed by adding the Chrome Driver binary to your system path.
- Next, if youโre testing on different machines or in a continuous integration environment, consider using Duskโs
--chromedriver-executableoption to point it at the exact location of your browser driver. This way, each machine can have its own trusty steed without confusion.
Oh, the joy of automation! But sometimes, even our trusty steed Laravel Dusk might need a little horse swap. Letโs talk about changing gears (or wheels, if you will) with ChromeDriver installations.
When you find yourself hankering for a different version of ChromeDriver than what our beloved dusk:install command bestows upon you, fear not! Just call upon the mighty dusk:chrome-driver command to step into a whole new world of ChromeDriver options.
composer require --dev chromedriver/chromedriver
There you go! Now go forth and conquer those tests with your preferred version of ChromeDriver! But remember, with great power comes great responsibility. Donโt forget to clean your stable (a.k.a. project directory) every once in a while to ensure a smooth-running test suite! ๐โโ๏ธ๐จ
Alrighty, party people! Letโs get this Laravel dance floor shaking with some ChromeDriver action! ๐บ๏ธ
First things first: You gotta make sure youโre rockinโ the freshest version of ChromeDriver for your OS (Operating System, not One Direction). Donโt be that guy at the party still rocking last yearโs cassette tape when everyone else is streaming in 4K.
So how do we get this dance going? Easy peasy! Just grab a drink, find a comfy spot on your couch (or, you know, if youโre feeling fancy, at your computer), and call up Laravelโs party planner:
php artisan dusk:chrome-driver
This command will serve you the latest ChromeDriver version that best matches your OS. Itโs like ordering a custom cocktail โ but instead of tequila and umbrellas, itโs ChromeDriver andโฆ well, still no umbrellas (sorry to disappoint).
Now youโre all set to join the Laravel dance party with a state-of-the-art ChromeDriver in tow! ๐๐๐ผ๐บ๏ธ๐ ๐ผ
Alright, buckle up, my coding comrades! Hereโs a dose of laughter and learning all rolled into one! Letโs install a snazzy version of ChromeDriver that matches your operating system like a glove. No more fumbling around with the basics; weโre about to elevate our Laravel Dusk test game with flair!
Ready? Set? Laugh and learn!
Drumroll please!
php artisan dusk:chrome-driver 86
Now, imagine this command as a slick, suave secret agent, slipping into your system, undercover as ChromeDriver 86. Just like when you finally found that elusive pair of platform boots on eBay (you know the ones!). But instead of rocking out at a disco, itโs ready to drive those tests like a pro!
So go ahead, and unleash this stylish undercover agent on your tests. Theyโll thank you for it โ trust me, they love a good ride in ChromeDriver 86!
Alright, buckle up, because weโre about to take a little trip through the world of web browsers - and no, itโs not quite as exciting as a rollercoaster ride at Six Flags, but bear with us. Hereโs your guide to installing a shiny new version of ChromeDriver for all your favorite operating systems (OSes? OS-i?).
Ready, set, go!
You may have already guessed it, but weโre about to summon the mighty power of Laravelโs Artisan to help us out. So letโs get our witchโs hat on and cast this spell:
php artisan dusk:chrome-driver โall
Now, that doesnโt sound like a spell for installing ChromeDriver, does it? Well, consider yourself initiated into the mysterious arts of Laravel wizardry. In simpler terms, what this command does is wave its magic wand (thatโs Artisan, remember?) over all supported operating systems and plants a fresh, juicy version of ChromeDriver in each one.
But why go through all this trouble, you might ask? Because, my friend, just like the right pair of shoes can make or break your dance moves on the dance floor, having the correct browser driver is essential for your tests to strut their stuff and shine like a star. So get ready to boogie down with ChromeDriver!
(Pssst: Just remember that this enchantment requires PHP 7.1.3 or higher to work its magic.)
Alrighty, letโs get this party started! ๐
First off, itโs time to play detective with our favorite browser, Chrome (or its open-source sibling Chromium)! But wait, before we dive in, make sure youโve got the right ChromeDriver for your OS operating system. No need to worry though, Laravelโs got your back! Just run this command like a super sleuth:
php artisan dusk:chrome-driver --detect
Attention
Remember, Dusk is a picky friend who needs his
chromedriverbinaries to be dressed up as executable files. If you find yourself in the middle of a Dusk standoff, ensure your binaries are looking sharp with this command:chmod -R 0755 vendor/laravel/dusk/bin/.
Now that weโve got our ChromeDriver in its Sunday best, letโs move on toโฆ oh, what did they call it? Oh yes! โUsing other browsers.โ Donโt worry, weโre not suggesting you switch to Internet Explorer (unless you have a time machine or a burning desire for nostalgia). Weโve got options like Firefox and Safari covered as well. But if you fancy a change, remember to install the correct driver for your chosen browser. Itโs all about choice in this browser wild west! ๐ค
So there you have it, folks! A little laughter, a lot of technical advice, and weโre off to the races with Laravel Dusk. Now go forth and test thy websites like never before! ๐
Unleashing the Browser Beast in Laravel Dusk!
By popular demand (okay, it was just one guy with a funny hat), Laravel Duskโs default beast of choice is Google Chrome, accompanied by a majestic ChromeDriver. But fear not, brave tester-knights, for you can summon your preferred browser to join the battle!
To begin this magical ritual, open up the ancient scrolls known as tests/DuskTestCase.php. This sacred text serves as the foundation for your Dusk tests, and by changing a single line here, youโll be able to summon other browsers like a modern-day Merlin!
/**
* Prepare for Dusk test execution.
*
* @beforeClass
*/
public static function prepare(): void
{
// No longer summoning the ChromeDriver by default, feel free to remove this line:
// static::startChromeDriver();
}
Once youโve banished the auto-summoned ChromeDriver, itโs time to create a custom driver! Youโll be using the enchanted RemoteWebDriver, which will connect to the URL and port of your choice. Additionally, you may cast spells on this driver by modifying its โdesired capabilities.โ
use Facebook\WebDriver\Remote\RemoteWebDriver;
/**
* Create the RemoteWebDriver instance.
*/
protected function driver(): RemoteWebDriver
{
return RemoteWebDriver::create(
'http://localhost:4444/wd/hub', DesiredCapabilities::phantomjs() // Change this to your desired browser and settings!
);
}
Now that youโve learned the art of summoning, go forth and conquer the browser world with your mighty Laravel Dusk tests! But remember, with great power comes great responsibility (and maybe some fun along the way). Happy browsing, knight! ๐ฐ๐ฒ๐
Ahoy there, code pirate! Letโs embark on a swashbuckling adventure in Laravel-landia! But first, ya gotta learn to walk before you can run a ship.
Setting Up Your Sailboat (Project)
To get started with your new Laravel project, grab your trusty terminal and type laravel new ProjectName, replacing โProjectNameโ with your pirate shipโs name. Yarr! Once thatโs done, you can navigate to your shiny new directory with the command cd ProjectName.
Generating Tests (Arrrrr-chitecting)
Now, ye might be wondering about those pesky tests, eh? No worries, matey! Laravel makes it easy for us to write tests. To generate a test for a specific class, sail over to the command line and type php artisan make:test ClassNameTest, where โClassNameโ is the name of your class that needs testing. Youโll find the new test file in the Tests directory, ready to be filled with testy goodness!
Running Your Tests (Swabbing The Deck)
Once youโve written some tests and are feeling confident, itโs time to run โem! Simply type php artisan test into your terminal, and Laravel will take care of the rest. If everything goes smoothly, youโll hear a cheer from the crew (or a single โArrr!โ if youโre sailing solo).
And Thatโs a Wrap (Walking the Plank)
Thatโs it, scurvy dog! Youโve now got yourself a Laravel project with tests that would make even Captain Jack Sparrow proud. If you need more details or want to learn about other treasures in Laravel-landia, donโt be shy โ dive into the official documentation! Happy coding, matey!
Alrighty, letโs get our coding capes on and dive into the whimsical world of Laravel Dusk test generation!
Making Magic Tests Happen
To conjure up a Dusk test faster than lightning, cast the dusk:make Artisan spell. The command will gracefully place your newly born test in the enchanted tests/Browser forest:
php artisan dusk:make LoginTest
Now, you might be wondering if our database needs a little fairy dust after each test. Worry not, dear coder! Each Dusk test comes with a built-in sprinkler that resets the database before it begins its dance of tests. Because who wants leftover cookies from yesterdayโs test, right? ๐ช๐ค๐ฆ
Happy testing, dear Laravel wizards! Let the enchanting journey of Dusk tests commence! ๐น๐๐
Oh, Database Reset 101 for Laravel Devs! ๐ป๐
Letโs face it, youโve probably been there - testing your application with data that looks suspiciously like last nightโs pizza toppings. Well, fret not! Laravel has got your back (or should we say, database?) with some fun-tastic ways to reset your database after each test! ๐๐
First off, remember when we said never use the RefreshDatabase trait in your Dusk tests? Well, itโs like that one friend who always offers you questionable leftovers. It might seem convenient, but trust us - you donโt want it for your database! ๐ท
Instead, there are two equally awesome options to choose from: DatabaseMigrations and DatabaseTruncation. Think of them as the yin and yang of database resets. Letโs break โem down:
The Great Migration (DatabaseMigrations) ๐ข
Ever heard about the good olโ days when everyone was moving west? Well, DatabaseMigrations is kinda like that for your database. It sets things up fresh by running your migration files - a one-way trip to Database Vacationland! ๐๏ธ
The Slim Trimmer (DatabaseTruncation) ๐ธ
If youโre more into minimalism and prefer a quick tidy-up rather than a full-on demolition, DatabaseTruncation is the trait for you! It keeps your existing tables but clears them out, leaving your database as clean and fresh as a new box of pasta! ๐
So go ahead, test away, and let Laravel handle the cleanup like a pro. Because who needs to scrub last nightโs pizza off their database when you can be writing awesome code instead? ๐๐
Alrighty then! Buckle up, because weโre about to dive into the thrilling world of Laravelโs DatabaseMigrations trait. This bad boy will ensure your database migrations are run before each test, like a well-oiled machine getting ready for showtime. But hold your horses! Dropping and recreating those databases tables for every test ainโt as fast as youโd think - itโs more sluggish than a sloth on a sugar high.
Truncating the tables is like taking a vacuum cleaner to your data, leaving it all intact but tidy. Hereโs how you can do it:
<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Symfony\Component\Console\Command\Command;
pest()->use(DatabaseMigrations::class);
// ... And just like that, we've tidied up the living room! Now let's test!
<?php
namespace Tests\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Symfony\Component\Console\Command\Command;
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
$this->artisan('database:truncate'); // ... and just like that, we've tidied up the living room! Now let's test!
}
}
[!WARNING] Now, for those of you who love SQLite in-memory databases, Iโve got some bad news - they canโt be used when executing Dusk tests. Itโs like trying to make a milkshake without a blender - it just wonโt work! The browser runs in its own process, and itโs like trying to reach into another dimension to grab a cup of coffee. Just stick with the regular databases for now, cowboy!
Oh, and before I forget - if you want to reset your database instead of just truncating it, hereโs how you can do it:
<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Symfony\Component\Console\Command\Command;
pest()->use(DatabaseMigrations::class);
// ... And just like that, we've torn down the old apartment and started building a brand new one! Now let's test!
<?php
namespace Tests\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Symfony\Component\Console\Command\Command;
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
$this->artisan('database:seed --class=ResetDatabase'); // ... And just like that, we've torn down the old apartment and started building a brand new one! Now let's test!
}
}
Alright, buckle up, database warriors! The DatabaseTruncation trait is your new best friend in the Laravel kingdom. This magical artifact will ensure your database tables are always squeaky clean and ready for action.
On the first test, itโll perform a full-blown migration to make sure your tables are built to perfection. But on subsequent tests, instead of re-running all those migrations (who has time for that?), itโll just give your database a quickie truncation, providing you with a much-needed speed boost.
Hereโs how to use this trait in Pest and PHPUnit:
<?php
* Party hard!
use Illuminate\Foundation\Testing\DatabaseTruncation;
use Laravel\Dusk\Browser;
pest()->use(DatabaseTruncation::class);
// End of the night...
<?php
namespace Tests\Browser;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTruncation;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class ExampleTest extends DuskTestCase
{
use DatabaseTruncation;
// Back to work tomorrow...
}
By default, this trait will spare the migrations table from being truncated. But if you want to customize your table selection, feel free to define a $tablesToTruncate property on your test class:
Note
Remember, in Pest, properties or methods should be defined on the base
DuskTestCaseclass or any class your test file extends.
/**
* Decide which tables get the axe.
*
* @var array
*/
protected $tablesToTruncate = ['users'];
Or, if you prefer to exclude specific tables from being truncated, define an $exceptTables property on your test class:
/**
* Exclude tables like the ones that store your precious data.
*
* @var array
*/
protected $exceptTables = ['users'];
To specify which database connections should receive a table-truncating makeover, create a $connectionsToTruncate property on your test class:
/**
* Choose your connection wisely.
*
* @var array
*/
protected $connectionsToTruncate = ['mysql'];
Finally, if you need to run some code before or after the database gets its well-deserved truncation, define beforeTruncatingDatabase or afterTruncatingDatabase methods on your test class:
/**
* Perform any work that should take place before the database has started getting chopped up.
*/
protected function beforeTruncatingDatabase(): void
{
// Do your thing!
}
/**
* Perform any work that should take place after the database has finished getting chopped up.
*/
protected function afterTruncatingDatabase(): void
{
// More magic here...
}
Now, go forth and make your databases sparkle like the night sky!
Unleashing the Beast (aka Running Tests)
Alright, champ! To get your browser tests roaring to life, unleash the mighty dusk Artisan command upon your terminal:
php artisan dusk
But what if last timeโs test results were more fail than Falcon heist? Fear not! You can save precious seconds (and sanity) by re-running only the disloyal tests with the dusk:fails command:
php artisan dusk:fails
The clever dusk command is not only a showoff, itโs also quite versatile! Just like the maestro conducting an orchestra, you can dictate which tests to perform with arguments usually accepted by the Pest / PHPUnit test runner. For example, if you want to run the tests for a specific group, just:
php artisan dusk --group=foo
Warning
If youโre using Laravel Sail to manage your local development environment, kindly check out the Sail documentation on configuring and running Dusk tests.
And remember, every beast needs its driver! To manually start chromedriver, you might need to:
export DISPLAY=:99
xvfb-run --auto -s :99 php artisan dusk:chrome
Happy testing, detective! (Or should we sayโฆ Dusketeer?)
Alrighty, letโs get this Laravel Dusk extravaganza started! ๐
Manually Firing Up ChromeDriver (Like a Boss)
If you find that the automatic ChromeDriver initiation isnโt cutting it for your one-of-a-kind setup, no worries, we gotchu covered! Just like a true maverick, you can kickstart ChromeDriver all by yourself before unleashing the dusk command. To do this, youโll want to put on your coding cowboy hat and pay a visit to the tests/DuskTestCase.php file.
Once there, find this here line that looks like itโs been called for backup:
/**
* Prepare for Dusk test execution.
*
* @beforeClass
*/
public static function prepare(): void
{
// static::startChromeDriver(); ๐จCall off the reinforcements!
}
Just comment out this line, and voilร โ youโve got yourself a manual ChromeDriver launching party! ๐๐
Now, if youโre feeling especially rebellious and decide to start ChromeDriver on a port other than the usual 9515 (we get it, you like to mix things up), fear not! All you need to do is modify the driver method of the same class to display your new port number with pride:
use Facebook\WebDriver\Remote\RemoteWebDriver;
/**
* Create the RemoteWebDriver instance.
*/
protected function driver(): RemoteWebDriver
{
return RemoteWebDriver::create(
'http://localhost:YOUR_NEW_PORT', DesiredCapabilities::chrome()
);
}
Ahoy there, Captain Testrunner! ๐ด Letโs set sail into the realm of Dusk and learn how to handle those environments like a seasoned seafarer! โต๏ธ
To get Dusk to use its own pirate map (environment file) when navigating treacherous testing waters, youโll need to hoist anchor at your projectโs root and create a .env.dusk.{pirate_ship} file. For instance, if ye be planning to launch the dusk command from yonder local port, then raise anchor with a .env.dusk.local parchment! ๐
Now, when those tests set sail and battle the high seas, Dusk will swab the decks by safely stowing away your regular .env map and rename the pirate map as the new captain (renaming it to .env). Once all the battles have been won and loot collected, Dusk will return your .env map to its rightful place! ๐ดโโ ๏ธ
Ahoy again! Remember to always wear an eyepatch while coding! Now letโs navigate to the browser basics and continue our swashbuckling adventure! Yarrrr! ๐
Ahoy there, coding pirates! Welcome to our swashbuckling guide onBrowser Basics - a treasure trove of knowledge you wonโt find in Captain Cookโs logbook! ๐ดโโ ๏ธ
Creating Browsers (Arrr, ye landlubbers!) ๐ค
Ah, the art of creating browsers! Itโs as easy as polishing a cutlass or mending a jolly roger. To embark on this journey, youโll need Laravel Valet and Homestead Improved. Theyโre like your shipโs compass and sextant, but for web browsing instead of sailing.
First, you should install these handy tools (itโs not called โpiratingโ without a little bit of looting, now is it?). Run the following command in your terminal:
composer global require laravel/valet && composer global require "berkeley/homestead-improved=~1.2"
Now, set sail for adventure! Letโs configure Homestead Improved by editing ~/.homestead. Donโt worry, itโs not like navigating the Bermuda Triangle; we promise youโll find your way back! After making any desired changes, save and close the file.
Once youโve done that, itโs time to kick off Homestead Improved:
homestead upgrade
And now, the moment weโve all been waiting for - firing up Laravel Valet! Start by running valet park, then create your first browser (yes, really) with this simple command:
valet browse local
Congratulations, matey! Youโve successfully created a browser. Ainโt that swell? ๐ฅณ
Accessing the Browser (Navigating to your treasure!) ๐ฐ
Now that youโve built your browser, itโs time to set sail and explore its depths. To do so, open up a web browser on your computer (you know, one of those things weโre trying to emulate). Navigate to http://local in the address bar. You should see Laravelโs welcome page - treasure chest and all!
Building Your Own Website (Yo ho, letโs create some gold!) ๐๏ธ
Building your own website is like carving a pirate ship out of wood; it takes time, patience, and a good olโ fashioned hook! To get started, create a new Laravel project:
laravel new my-pirate-site
Now, sail on over to your browser (the one you created earlier, donโt forget!) and navigate to the new project: http://local.my-pirate-site. You can start building your treasure trove of a website from here! ๐ดโโ ๏ธ
Extending Browsers (Adding plank-walking sharks, because why not?) ๐ฆ
Why settle for a plain olโ browser when you can have one with a built-in shark plank? To extend your browser, create a new Laravel package and integrate it into your browser. Itโs like adding a parrot or a peg leg to a pirate!
But thatโs another adventure for another day, matey! Letโs set sail on building your own pirate-themed web browser with Laravel. Fair winds and following seas! ๐ฌ๏ธโ๏ธ
Alrighty then! Letโs dive into creating browsers, shall we? First things first, letโs write a test that verifies our app is as friendly as a puppy at a pet store. After whipping up a test (pro tip: donโt forget the treats), we can tweak it to navigate to the login page, enter some credentials, and click the โLoginโ button โ all without getting our digital paws dirty! To create a browser instance, you can summon the mighty browse method from within your Dusk test.
<?php
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use App\Traits\HasASpiritOfAdventure; // Because every browser needs a little excitement!
pest()->use(DatabaseMigrations::class, HasASpiritOfAdventure::class);
test('basic example', function () {
$user = User::factory()->create([
'email' => 'taylor@laravel.com',
]);
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login') // Off we go on a grand adventure!
->type('email', $user->email)
->type('password', 'password')
->press('Login')
->assertPathIs('/home'); // Mission accomplished, time for tea and crumpets!
});
});
<?php
namespace Tests\Browser;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use App\Traits\HasASpiritOfAdventure; // Because every browser needs a little excitement!
class ExampleTest extends DuskTestCase
{
use DatabaseMigrations, HasASpiritOfAdventure; // Buckle up, it's time for adventure!
/**
* A basic browser test example.
*/
public function test_basic_example(): void
{
$user = User::factory()->create([
'email' => 'taylor@laravel.com',
]);
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login') // Off we go on a grand adventure!
->type('email', $user->email)
->type('password', 'password')
->press('Login')
->assertPathIs('/home'); // Mission accomplished, time for tea and crumpets!
});
}
}
As you can see in the examples above, the browse method is like a digital Sherpa that accepts a closure. A browser instance will magically appear by Duskโs enchantment, ready to be your trusty sidekick as you explore and interact with your app!
Alright, letโs get this party started!
Unleashing the Power of Polymorphous Porcupines (AKA Multiple Browsers)
When life gives you lemons, it might as well give you a dozen different browsers to ensure your tests are as squeaky clean as a well-oiled browser quirk machine! Take, for instance, our chat screen thatโs got the wires of websockets all crossed up. To untangle this mess, we need to put on our detective hats (or in this case, chrome domes) and whip out some polymorphous porcupines!
You see, creating multiple browsers is as easy as adding more browser arguments to the signature of the closure bestowed upon the browse method. Yes, itโs time for a little bit of old-fashioned polymath party, Laravel style!
$this->herdOfPorcupines(function (Browser $quill, Browser $inkwell, Browser $scribble) {
$quill->logInAs(User::find(1))
->navigateTo('/home')
->waitForText('Message in a bottle');
$inkwell->logInAs(User::find(2))
->navigateTo('/home')
->waitForText('Message in a bottle')
->type('message', 'Yo, Taylor!')
->clickOn('Send the darn message already');
$scribble->waitForText('Yo, Taylor!')
->assertSee('Jeffrey Way is in the chat too');
});
Now, who needs boring old multiple browsers when youโve got a herd of polymorphous porcupines at your fingertips? Letโs get testing, cowboy (or cowgirl)!
Ahoy there, Laravel Captain! Prepare to set sail on a journey through your applicationโs URL seas with the visit method!
Steer your ship towards the login port:
$browser->visit('/login');
Fancy yourself a map reader? Use the visitRoute method to navigate to a named route, like a seasoned treasure hunter:
Set sail for the route named "GoldenTicket":
$browser->visitRoute($routeName, $parameters);
Ever wanted to turn back time? Now you can with the back method!
Remember the last port-o'-call:
$browser->back();
And if youโve found yourself in a pickle and need to reload, use the forward method!
Aye, rewind that compass:
$browser->forward();
Feeling queasy? Refresh your page with the refresh method:
Sea-sick? Spin the wheel:
$browser->refresh();
And remember to always keep an eye on that horizon, Captain! Now, hoist the sails and set course for adventure! ๐ด๐ข๐
Alright, buckle up, web-explorers! In this thrilling expedition of digital domination, weโre about to embark on a journey that will make you the master of your browserโs destiny. Grab your mouse and keyboard, put on your superhero cape (optional), because weโre diving into the world of Laravel Dusk resizing!
First off, ever felt like the browser window is a giant T-Rex in a dollhouse? Well, no more! With the resize method, you can now be the Jurassic Park ranger and shrink that beast to a manageable 1920 x 1080.
$browser->resize(1920, 1080); // This is your browser on a leash!
Next up, youโre the host at the worldโs most exclusive popcorn cinema. The maximize method is your โhouse lights offโ moment - maximize that browser window and enjoy the show!
$browser->maximize(); // Popcorn, please!
The fitContent method is like having a personal assistant who adjusts your TV settings based on whatโs playing. It resizes the browser to match the content size:
$browser->fitContent(); // Your browser just got smarter... and sassier!
Now, when things donโt go according to plan (as they rarely do in our line of work), Dusk will automatically adjust the browser window for you. But if you want some privacy, you can disable this feature by calling disableFitOnFailure.
$browser->disableFitOnFailure(); // Nothing to see here, move along!
Finally, we come to the move method. Imagine being a Jedi with the power to teleport your browser across the screen.
$browser->move($x = 100, $y = 100); // May the mouse be with you!
Now go forth and conquer those browsers! But remember, with great power comes great responsibility โ donโt forget to test often and have fun!
Browser Magic Tricks!
If youโre a fan of repetition and hate typing the same thing over and over in your tests, weโve got some spellbinding news for you! In Laravel Dusk, you can conjure up custom browser incantations using the macro method on the enchanting Browser class.
To put this sorcery into practice, cast the charm from a service providerโs boot spell:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Browser;
class WizardryServiceProvider extends ServiceProvider
{
/**
* Register Dusk's browser spells.
*/
public function boot(): void
{
Browser::macro('waveWandAtElement', function (string $element = null) {
$this->script("$('html, body').animate({ scrollTop: $('$element').offset().top }, 0);");
return $this;
});
}
}
The macro function accepts a name (think Abracadabra) as its first argument and a closure as the second. When you summon this spell as a method on your bewitched Browser instance:
$this->enchant(function (Browser $browser) use ($user) {
$browser->navigateTo('/pay')
->waveWandAtElement('#credit-card-details')
->ensureTextExists('Enter Credit Card Details');
});
Now, instead of performing those tedious scrolls with your mouse, let the magic handle it! ๐ฉโจ
Alrighty, buckle up, test cowboys and cowgirls! When you find yourself roaming the digital frontier of pages protected by good olโ authentication, fear not! Dusk has a trusty sidekick called loginAs to help you bypass those pesky login screens during every test ride.
Hereโs how it works: just like calling your deputy for backup, you can summon the loginAs method in your tests:
use App\Models\User;
use Laravel\Dusk\Browser;
It's high noon in the testin' sheriff office! (function (Browser $browser) {
$browser->loginAs(User::find(1)) // Yep, that's our trusty deputy we're calling here
->visit('/home'); // And here's our destination
});
[!WARNING]
Now, hold your horses! Using the loginAs method means that user session will stay put for all tests within this here file. So watch out for any unintended posse member joining your test ride!
Oh, and if youโre curious about those cookie jar-like entities, Dusk uses Laravelโs cookies to manage user sessions during testing. You can find more details on that here. Just like a cowboy learninโ the ropes, youโll soon be a pro at it!
Yeehaw and happy testing!
Cookies Galore! ๐ช
In this digital bakery we call the web, cookies are more than just treats you get from a vending machine. With Laravelโs magical cookie jar (aka cookie method), you can either peek into or whip up an encrypted deliciousness like so:
peek in the jar: $browser->cookie('name');
bake a new one: $browser->cookie('name', 'Taylor');
But what if youโre making sugar-free cookies for your low-key frenemy Matt? Donโt worry, weโve got plainCookie to the rescue, allowing you to make unencrypted cookies that even Matt wonโt be able to hack:
sugar-free: $browser->plainCookie('name');
bake a low-key cookie: $browser->plainCookie('name', 'Taylor');
Life can get messy in the digital kitchen, so when you need to clean up and remove that pesky โnameโ cookie:
$browser->deleteCookie('name');
Now go forth and bake those cookies (or delete them, whatever your heart desires)! ๐ค๐ช๐
Ahoy there, coding pirates! Sail the seas of JavaScript with Laravelโs swashbuckling script method! Itโs the key to executing your wildest browser-based adventures:
Steer your ship towards $browser->script('document.documentElement.scrollTop = 0');
Set anchor at $browser->script([
'Ahoy matey, set body scroll to zero!',
'Yo ho ho, adjust documentElement scroll to zilch!'
]);
Furl the sails and let's grab some loot with $output = $browser->script('return window.location.pathname');
Ye be scouring for a way to take a peek at your browserโs viewport, eh? Fear not, matey! The script method can also help ye capture the perfect screenshot:
$browser->screenshot('treasure-map.png');
Thatโs all, mateys! Now set sail for new adventures with Laravelโs enchanted script and screenshot methods! May your voyages be swift and your code clean!
Catching Luminous Frames in Laravelโs Web of Wonders!
Venture into the world of snapshots, dear web wanderers! The screenshot function is your trusty sidekick here. Itโll help you capture a screenie and stash it away with a name of your choice, all inside the tests/Browser/screenshots hideout:
$browser->screenshot('my-super-secret-memento');
Next up, we have the responsiveScreenshots function! This oneโs like a superhero with multiple screens, capturing shots at various breakpoints:
$browser->responsiveScreenshots('my-ultra-responsive-screenshot');
Last but not least, the screenshotElement function is your secret weapon for snapping that pesky elusive element on the page:
$browser->screenshotElement('#the-one-that-got-away', 'my-elemental-evidence');
And remember, a picture may be worth a thousand words, but in this case, itโs also worth a spot on your disk! ๐ธ๐พ
Unleash your Inner Geek: Logging Browser Console like a Pro! ๐๐ป
Welcome, dear code wranglers, to the mystical world of logging browser console output! And what better way to do it than with Laravelโs enchanted storeConsoleLog spell?
Here comes the incantation:
$browser->storeConsoleLog('filename');
Just like a Jedi master casting a spell, you can harness the power of this method to save your browserโs console output in the tests/Browser/console directory. Itโs like having an ever-growing scroll filled with debugging goodness! ๐๐
But remember, only use it wisely, for good, and not for mischief or pranks, lest you find yourself banished to the land of PHP warnings! ๐๐๐ซ
Alright, tech whizzes! Buckle up for a rollercoaster ride through Laravelโs wondrous world of code! Today, weโre gonna learn about the magical storeSource method - a tool so powerful it could make even Muggles do some serious web dev magic.
You might be wondering: โWhat on Earth is this sorcery you speak of?โ Well, my dear friend, when you cast this spell on your browser, itโll transform the current pageโs source into something tangible - a file on your disk! Yes, you read that right, a real, live file!
Hereโs how to summon storeSource:
$browser->storeSource('your_fancy_filename');
Now, where does this enchanted file end up? Well, it gets whisked away and deposited within the mystical tests/Browser/source directory โ a place that even Google Maps canโt find! But fear not; the files are safe there, ready to be summoned whenever you need them.
And with that, our lesson on Laravel sorcery comes to an end. May your pages be well-sourced and your coding always be enchanted! โจ๐ฎ๐ป
Ahoy there, Laravel coders! Buckle up for a whirlwind tour of our trusty sidekick - Duskโs magical Selector Wand! ๐ญ๐ซ
๐ Dusk Selectors ๐
In the realm of testing, finding the right element can be akin to locating a needle in a haystackโฆor a unicorn in a field of mules. But fear not! Duskโs Selector Wand makes this task as easy as pie (okay, maybe not that easy, but itโs definitely easier).
Just like Hagrid casting Expelliarmus to disarm enemies, you can use CSS selectors with Dusk to find and manipulate elements in your Laravel application.
๐ฏ CSS Selectors ๐ฏ
These mystical incantations help you single out specific elements within your HTML like a seasoned witch or wizard. Hereโs a quick rundown of the most commonly used ones:
- Tag Name: This is your basic spell, perfect for beginners. Example:
div,a, orbuttonselectors. - Class Names: For those who have graduated from potion-making 101. Example:
.my-class. - ID Selectors: Youโre now ready to perform advanced charms! Use IDs like a beacon to find that one elusive element. Example:
#my-id. - Attribute Selectors: You can even cast spells based on attributes of elements (their hair color, perhaps?). Example:
[href="https://example.com"]. - Child Selectors: If youโre looking for an element nestled deep within your HTML family tree, this spell is just what the doctor ordered. Example:
div > a.
๐ญ Using Dusk Selectors ๐ญ
Now that youโve brushed up on your CSS selector spells, itโs time to unleash them upon your Laravel application with Dusk! Just remember, practice makes perfect (or at least less bewildered). ๐
// This example demonstrates using a class name and ID selector in Laravel Dusk tests.
it('can interact with elements', function () {
$this->browse(function (Browser $browser) {
// Select element by its class name
$button = $browser->elements('.my-class');
// Perform an action on the selected button
foreach ($button as $element) {
$element->click();
}
// Now let's find the element with the ID 'my-id' and assert something about it
$element = $browser->find('#my-id');
expect($element)->toBeVisible();
});
});
Remember, dear developer, mastering Duskโs Selector Wand is your first step towards conquering the tests of Laravel land. Happy coding! ๐ฉโ๐๐
Ah, the age-old conundrum of writing Dusk tests! Itโs like trying to find a needle in a haystackโฆ of CSS selectors. You know the drill โ frontend tweaks can send your carefully crafted test cascading down like dominoes, leaving you with a broken test and an empty feeling of frustration.
<button>Login</button>
$browser->click('.login-page .container div > button'); // Oh no! Your test just got 'logged off' by a sneaky CSS update!
But fear not, my friend! Dusk selectors are here to save the day. With these bad boys, you can focus on writing effective tests instead of playing detective with your CSS selector knowledge. To define a selector, simply slap a dusk attribute onto your HTML element like so:
<button dusk="login-button">Login</button>
And when itโs time to interact with the attached element in your test, just prefix the selector with @:
$browser->click('@login-button'); // And voila! Your test remains unbroken.
If you fancy customizing the HTML attribute that Dusk selectors use, you can do so using the selectorHtmlAttribute method. Typically, youโll want to call this from the boot method of your applicationโs AppServiceProvider:
use Laravel\Dusk\Dusk;
Dusk::selectorHtmlAttribute('data-dusk'); // Now your selectors will use 'data-dusk' instead of 'dusk'. Go wild!
Happy testing, and may your tests always be as stable as a rock in a hurricane!
Alright, buckle up, code cowboys and codettes! Weโre about to venture into the wild frontier of Laravel configuration settings, where text, values, and attributes gallop together in harmonious chaos.
First off, letโs wrangle those settings like a seasoned ranch hand. You can fetch them with a simple config() function call. For instance:
$mySetting = config('app.my_setting');
Now, if you want to lasso your settings and give โem a makeover, you can set new values using the handy-dandy dot notation. Hereโs how to rope in some changes:
config(['app' => ['my_setting' => 'new_value']]);
But what about them attributes, you ask? Well, partner, Laravel has got your back with environment-specific configuration. You can herd your settings into different pastures (environments) like development, testing, and production, using the env() function:
$myDevSetting = env('APP_MY_DEV_SETTING', 'default value');
And if youโre feeling particularly feisty, you can even register your own custom attributes! Saddle up and check out the official documentation for more details on this lasso-dazzling feature.
Remember, cowpokes and cowgirls: Laravel configuration settings are your trusty steed when it comes to managing the intricacies of your applicationโs back end. So donโt be shy โ wrangle those settings with panache!
Ah, Dusk โ the dancing diva of web testing! Letโs dive into her captivating choreography of retrieving and setting values on your page. Just imagine Dusk as a charismatic maestro, conducting an orchestra of HTML elements to dance at your command!
First act: Retrieval time! Want to know whatโs cookinโ in an element matching a given selector? No problem! Just call upon Dusk and whisper the magic incantation:
// Summon the value...
$value = Dusk\Browser::call('get_the_goods', 'selector'); // Because who doesn't love a good theater reference, right?
Next up: The showstopper! Ever needed to set the value of an element like a certain CSS or Dusk selector? Hereโs your backstage pass:
// Set the scene with a new value...
Dusk\Browser::call('set_the_scene', 'selector', 'value'); // Now that's what I call a script rewrite!
In between acts, letโs take a quick intermission and talk about inputValue. This little number is perfect for when you need to get the value of an input element with a specific field name. So, call upon Dusk:
// Get the star of the show...
$value = Dusk\Browser::call('spotlight', 'field'); // And don't forget your pompoms!
Now that weโve got you hooked, letโs move on to the next section! Who knows what other magical tricks Dusk has up her sleeves? Letโs find out together! ๐ญ๐๐ผโจ
In the grand tradition of digital sleuthing, allow me to introduce you to the most intriguing method since Sherlockโs โElementaryโ, dear Watson! Behold, the magnificent text method!
This cryptic commander can be summoned to unveil the secret identity of an element hidden behind a selector shield:
$mysteryText = $browser->text('the-selector-that-dares-not-speak-its-name');
Now, imagine youโre in a swanky Victorian drawing-room, where every object is whispering its secrets. With the text method, you can eavesdrop on that chatter and decipher the hidden messages!
Alrighty, buckle up, coding cowboys and codelettes! Letโs dive into the magical world of Laravel attribute wrangling where we tame those HTML elements with a dash of PHP magic.
First off, weโve got our trusty steed, the attribute method. This cowboyโs lasso is perfect for grabbing an elementโs attribute value by its selector and โropeโ (which in this case is โvalueโ). So, if you want to know the secret ingredient of your formโs action or the color of that fancy button, just give attribute a spin:
$secret_ingredient = $browser->attribute('form-selector', 'action');
$button_color = $browser->attribute('button-selector', 'style'); // Note the 'style' instead of color because not all browsers support the 'color' attribute on HTML elements.
Now, remember to keep your lasso sharp and your fingers nimble, because next time we saddle up for another Laravel adventure! Yee-haw! ๐ค ๐
Ahoy there, adventurous coder! Buckle up for a whirlwind tour of Laravelโs form-taming tactics. Letโs dive into the world of interaction, where keyboards and forms unite to conquer the digital frontier! ๐
Typing Values Directly Into Request
You might be asking yourself, โHow can I obtain user input straight from the form request?โ Well, my friend, thatโs easier than convincing a cat to use a computer! Simply access the incoming data via the request() global helper:
$name = $request->input('name'); // Fetch the 'name' value from the user input
Just remember, this approach might make you vulnerable to Cross-Site Scripting (XSS) attacks. To avoid such dangers, use data sanitization techniques like Laravelโs built-in htmlspecialchars() function:
$name = htmlspecialchars($request->input('name')); // Safer way to fetch and display user input
Retrieving Input From Forms
What if your form has a name attribute thatโs as long and winding as the Nile? No worries! Laravel provides an automatic binding mechanism for forms. Just define your form field names in the same way you would with HTML:
<form method="POST" action="/submit">
<!-- ... -->
<input type="text" name="user_name">
</form>
Now, in your controller, Laravel will automatically bind the input to a property with the same name:
public function submit(Request $request) {
// Access user's name directly via $request->user_name
$userName = $request->user_name;
}
So now you can tackle forms like a seasoned web developer, and impress your cat-friends with your newfound Laravel form-taming prowess! ๐ฑโ๐ค๐
Ahoy there, Captain! Sail the seas of web automation with Dusk, your trusty Laravel testing companion!
First off, letโs chat about how to fill out forms like a seasoned pirate. You donโt need Yarr-arrrโs CSS selector to type into an input field (though it can be helpful in a sea of similar fields). Hereโs the jist:
$browser->type('email', 'taylor@laravel.com');
But, if you do want to set sail with a CSS selector, Dusk will search for an input or textarea field with the provided name attribute like a seasoned buccaneer!
Now, suppose ye want to add more grog (or comma-separated values) without clearing the current contents. Fear not, for we have the append method:
$browser->type('tags', 'foo')
->append('tags', ', bar, baz');
To empty a field faster than Captain Jack Sparrow downs rum, use the clear method:
$browser->clear('email');
Want Dusk to type as slow as a sea shanty being sung by a drunken sailor? Use the typeSlowly method! By default, it pauses for 100 milliseconds between key presses, but you can adjust the speed:
$browser->typeSlowly('mobile', '+1 (202) 555-5555');
$browser->typeSlowly('mobile', '+1 (202) 555-5555', 300);
And, for adding text at a leisurely pace, thereโs appendSlowly:
$browser->type('tags', 'foo')
->appendSlowly('tags', ', bar, baz');
Ahoy and happy testing! May your tests be as reliable as a shipโs compass, and your code as steady as the deck underfoot. Arrr matey! ๐ดโโ ๏ธ
Alrighty then! Letโs dive into the whimsical world of Laravel dropdowns, where selecting values is akin to picking your favorite flavor of space ice cream. ๐๐ฆ
To choose a scoop from a select element, you can use the select method. Unlike your picky toddler, this method doesnโt demand a full CSS selector, making it a breeze to navigate even the messiest webpage playpens. When offering up a flavor (er, value) for selection, remember to pass the scoopโs secret code, not its catchy name:
$browser->select('size', 'Large'); // A hearty scoop of Large!
If you fancy rolling the dice and letting fate decide your ice cream destiny, simply skip the second argument:
$browser->select('size'); // Let's see what unexpected flavor awaits us!
But, my dear web traveler, what if you canโt decide between Art and Music? Well then, youโre in luck! By passing an array as the second argument to the select method, youโre essentially inviting both Art and Music for a scoop date. Or in Laravel terms:
$browser->select('categories', ['Art', 'Music']); // A double-scoop delight of Art & Music!
And thatโs the cosmic scoop on Laravel dropdowns! Now, go forth and conquer those web forms with style and a smile. ๐๐
Ah, the thrill of ticking off boxes! Who knew that programming could be soโฆ satisfying? In the Laravel realm, weโve got a little something called the โcheckโ method, a charm that ticks your checkboxes without breaking a sweat. No need for a full CSS selector here, just point it at the desired checkbox using its good olโ name attribute:
$browser->check('terms');
But what if you change your mind? No worries, weโve got the โuncheckโ method to help you backtrack without any drama. Just use it like this:
$browser->uncheck('terms');
Now thatโs some friendly interface interaction! Next stop: Radio Buttons โ where one button must always be left out to keep things interesting. Stay tuned, folks! ๐ข
Ahoy there, Laravel swashbucklers! Letโs dive into the captivating world of radio buttons - those charming circular chums that help us make choices when we canโt decide between pizza or pasta (or both, amirite?).
To ensure your radio button plays its part in this grand production, you can employ the enchanting radio method. Fear not, dear friend, for it is as simple as pie (and we all know pies are amazing!). Unlike some other methods that demand a full cast of CSS selectors, our humble radio button just needs its name and value to be recognized - like your long-lost brother youโve only just met on Facebook.
$browser->radio('size', 'large');
Just imagine if Facebook used a similar matching algorithm for potential matches โ life would be one big happy family! But alas, back to the task at handโฆ If our trusty browser canโt find a suitable radio button with matching name and value, it will embark on an epic quest, akin to El Dorado, to unearth its intended target.
So there you have it, intrepid Laravel adventurers! Go forth and conquer the world of radio buttons with this newfound knowledge. And remember: when in doubt, choose pizza (and pasta)! ๐๐๐
Unleashing Your Inner Muppet with File Attachments
Got a file youโd like to slap onto an HTML form? Fear not, dear friend! Laravelโs got the perfect trick for you. Introducingโฆ the attach method! Itโs like the magic hand of Kermit himself, reaching out and grabbing your precious files with ease.
No need to bust out advanced CSS selections here - just point it towards a file input element. If our friendly little helper canโt find a match using its magical powers (erโฆ CSS), itโll simply search for a file input with the same name as your file! How thoughtful is that?
$browser->attach('photo', __DIR__.'/photos/mountains.png');
[!Attention-Grabber] But wait, before you start your symphony of furry friends, remember: The attach function is a little picky and demands the
ZipPHP extension to be installed and humming away on your server. So donโt forget to check if Kermitโs got his guitar tuned!
Alright, buckle up, my friend! Hereโs the scoop on pressing buttons in Laravelโs Dusk testing suite. This ainโt your mamaโs button-clicking; weโre talkinโ code thatโs as sharp as a well-timed dad joke.
The press method is the unsung hero of clicking button elements โ itโs like saying โclick meโ to the computer in PHP! You can either feed it the buttonโs display text or drop a CSS/Dusk selector for some extra precision:
$browser->press('Login'); // Just like saying "Hey login, I'm here!" to the webpage
Now, when it comes to submitting forms, thereโs this sneaky little trick many apps play โ they disable the submit button after you click it, and only re-enable it once the form submissionโs HTTP request is complete. Donโt worry, we got a workaround! The pressAndWaitFor method will click the button and then patiently wait for it to be re-enabled, like your grandma waiting for her favorite soap opera to come on:
// Click that Save button, and wait up to 5 seconds for it to enable...
$browser->pressAndWaitFor('Save');
// Click the Save button, but this time we'll only wait a maximum of 1 second...
$browser->pressAndWaitFor('Save', 1);
Now that youโre all clued up on clicking buttons and links, go out there and conquer the web with your newfound skills! And remember, if it ainโt broken, just click it harder. (Disclaimer: do not actually click things harder โ thatโs not how programming works.) ๐
Navigating Links like a Web Surfinโ Pro! ๐๐โโ๏ธ
Alright, party people, letโs talk about clickinโ links in this here Laravel Dusk playground! To get the job done, you can use the clickLink method, which acts like a digital finger tap on the link with the specified text:
$browser->clickLink($linkText);
Now, if you want to make sure that link is actually showing up, instead of being a no-show or M.I.A., use the seeLink method:
if ($browser->seeLink($linkText)) {
// Hooray! The link's visible. ๐ Let's continue with our surfing adventure!
}
[๐จ Attention all web surfers!] These methods groove along to jQuery tunes. If the party ainโt started yet (jQuery isnโt on the page), Dusk will bust a move and bring it on stage for the whole test, ensuring a rhythmic ride for everyone! ๐บ๐
Alrighty, letโs get this party started! The keys method in Laravel Dusk is like the secret sauce that turns your browser into a dancefloor where you can bust out some intricate moves that even Usher would be impressed by. ๐๐บ
Usually, the type method is like inviting your date for a slow dance, but with keys, youโre breakdancing on the dancefloor and pulling off some crazy combos! Imagine this: you can hold down the shift key while entering โtaylorโ into an element like a boss ๐
$browser->keys('selector', ['{shift}', 'taylor'], 'swift');
But wait, thereโs more! Ever wanted to send a secret message to your app using keyboard shortcuts? Well, now you can! Just point the browser at the main CSS selector for your application and unleash the power of a keyboard combo:
$browser->keys('.app', ['{command}', 'j']);
[โ ๏ธ Warning!] Remember, all cool modifier keys like
{command}are wrapped in{}characters and theyโre not just any old keys - theyโre the superheroes of the keyboard world, defined in theFacebook\WebDriver\WebDriverKeysclass (which you can find on GitHub here: https://github.com/php-webdriver/php-webdriver/blob/master/lib/WebDriverKeys.php).
Now that you know about this magical keys method, go forth and conquer the digital dancefloor! ๐ป๐
In the realm of Laravelโs Dusk, where browser interactions are the bread and butter, the withKeyboard method is your secret sauce for whipping up intricate dance routines with your trusty keyboard! This magical technique brings forth the mighty Laravel\Dusk\Keyboard class.
Now, this keyboard isnโt just any ordinary kitchen appliance. It boasts some fancy moves like press, release, type, and even a pause for added dramatics (or to simulate your coffee break).
Hereโs a fun example that could possibly make your browser dance the Charleston:
use Laravel\Dusk\Keyboard;
$browser->withKeyboard(function (Keyboard $keyboard) {
// Cue: The introduction of our star performer, 'c'!
$keyboard->press('c');
// Pause for dramatic effect... or for that much-needed coffee refill.
$keyboard->pause(1000);
// Release 'c', setting the stage for our next moves.
$keyboard->release('c');
// Now, let's type a little love letter to our browser with 'ceo'.
$keyboard->type(['c', 'e', 'o']);
});
And there you have it! With these keyboard macros, your tests can now dance, sing, and perform complex interactions like a seasoned Broadway star! Keep on codinโ and having fun!
Alright, letโs get this keyboard party started! If youโre hankering to define some custom dance moves for your fingers that you can bust out across your test suite like a digital Riverdance, then look no further than the macro method provided by the oh-so-sexy Keyboard class.
Now, you should call this shindig from a service providerโs booty-shakinโ boot method (we didnโt say it was a refined crowd):
<?php
namespace App\Providers;
// Import some friends for the dance floor...
use Facebook\WebDriver\WebDriverKeys;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Keyboard;
use Laravel\Dusk\OperatingSystem;
class DuskServiceProvider extends ServiceProvider
{
/**
* Register Dusk's browser macros.
*/
public function boot(): void
{
// Define your first move - the copy-cat cha-cha:
Keyboard::macro('copy', function (string $element = null) {
// If you're on a Mac, press and hold the Command key...
if (OperatingSystem::onMac()) {
$this->type(WebDriverKeys::META);
} else {
// ...otherwise, it's Control for everyone else!
$this->type(WebDriverKeys::CONTROL);
}
// Then press 'c' - no need to hold it like a corsage!
$this->type('c');
});
// Next up is the paste party:
Keyboard::macro('paste', function (string $element = null) {
// If you're on a Mac, press and hold the Command key...
if (OperatingSystem::onMac()) {
$this->type(WebDriverKeys::META);
} else {
// ...otherwise, it's Control for everyone else!
$this->type(WebDriverKeys::CONTROL);
}
// Then press 'v', and let the magic flow!
$this->type('v');
});
}
}
Once youโve defined your moves, itโs time to hit the dance floor:
$browser->click('@textarea')
->withKeyboard(fn (Keyboard $keyboard) => $keyboard->copy())
// Pause for dramatic effect...
->sleep(1000)
->click('@another-textarea')
->withKeyboard(fn (Keyboard $keyboard) => $keyboard->paste());
Now thatโs what I call a well-choreographed test suite! Keep on dancing, keyboard warrior. ๐๐บ๏ธโจ
Ahoy there, coders! Letโs embark on a jolly journey through Laravelโs enchanting world of mouse magic! ๐ญ
Navigating the UI like a pirate
Congratulations, ye scurvy sea dogs! Youโve conquered the code oceans and now youโre ready to command the mouse deck. Clicking on elements is as easy as plundering treasure chests! ๐ดโโ ๏ธ
To click on an element in Laravel, all ye need is a trusty old jQuery click() function. Here be an example:
use Jenssegers\Agent\Facades\Agent;
// Check if the user is using a touch device or not
if (! Agent::touch()) {
// Click on the 'submit' button
$('#your-form').find('button[type="submit"]').click();
}
Triggering Events like a Wizard!
Welcome to the mystical realm of event conjuring! With Laravelโs help, ye can make elements dance and sing just by waving your mouse (or finger, if ye be using a touch device).
To trigger an event in Laravel, employ the power of jQueryโs trigger() function. Here be an example:
// Trigger a 'click' event on an element with the class 'your-element'
$('.your-element').trigger('click');
Prepping for Mobile Navigation like a Sailor!
Ahoy, mateys! Prepare to conquer the seven seas of mobile navigation with Laravelโs assistance. The touch events are no different from the click eventsโjust use jQueryโs touchstart() and touchend() functions instead.
// Trigger a 'touchstart' event on an element with the class 'your-element'
$('.your-element').on('touchstart', function(e) {
// Your code goes here!
});
Remember, me hearties: Laravel is but a humble helper in your pirate journey. But with these mouse and touch event tricks under yer belt, youโre ready to rule the oceans of code! Yarr! ๐ด๐
Ahoy there, brave coder! Sail into the sea of interaction with Laravel Dusk, and letโs talk about clicking elements. Shiver me timbers, ye wouldnโt believe how easy it is to click on an element like a pirate swabbing the deck!
$browser->click('.selector'); // Clicking on an element using CSS selector, matey!
But what if ye fancy a more precise target? Fear not, for the clickAtXPath method is at yer service.
$browser->clickAtXPath('//div[@class = "selector"]'); // Navigating like Captain Ahab hunting Moby Dick!
And what if ye want to click on a specific spot, say where Long John Silverโs treasure chest might be hidden? You can use the clickAtPoint method for that.
$browser->clickAtPoint($x = 0, $y = 0); // Pointing and clicking with laser-like precision!
Now, if yeโre feeling extra enthusiastic and wanna double click like Jack Sparrow on a treasure map, go ahead:
$browser->doubleClick();
$browser->doubleClick('.selector'); // Double tapping that map with a hearty pirate grip!
For those times when ye need to show the black flag, use the rightClick method:
$browser->rightClick();
$browser->rightClick('.selector'); // Raising the Jolly Roger on that element with a flick of the wrist!
If ye want to hold down the mouse button like Captain Barbossa in pursuit, use clickAndHold. Donโt forget to release it with releaseMouse.
$browser->clickAndHold('.selector');
$browser->clickAndHold()
->pause(1000) // Pause for dramatic effect, of course!
->releaseMouse(); // Letting go after a good long hold!
Lastly, if ye want to control-click something like Will Turner did with the compass, use the controlClick method.
$browser->controlClick();
$browser->controlClick('.selector'); // Controlling that element as if by magic!
So there ye have it, matey! Dive into the world of Laravel Dusk interaction with these handy methods at yer service. Yarr-garsh-gumment!
Ahoy there, Laravelers! Sail into a new sea of web interaction with the magical mouseover method! This enchanted incantation is just what you need when you want to perform sorcery on elements that fit your stylish CSS or Dusk wardenโs fancy:
$browser->whisperCharm('.selector'); // Or, if you prefer, use the more formal `mouseover` instead
Just remember, the key to casting this spell is having a keen eye for selectors and a mouse with a curious wandering instinct! ๐งโโ๏ธ๐ญโจ
Ahoy there, coding cowboy! Letโs dive into the wild west of Laravel interaction, where you can wrangle elements like a seasoned wrangler. In this frontier town, we got ourselves a handy drag method thatโll let you move an element around faster than a greased pig at a county fair!
$browser->drag('.from-selector', '.to-selector'); // Move 'em from one spot to another like a pro cowboy!
But wait, partner! If youโre feeling fancy and want to guide your element down a specific path, we got ya covered. Hereโs how to steer โem left, right, up, or down:
$browser->dragLeft('.selector', $pixels = 10); // Move it to the left, yeehaw!
$browser->dragRight('.selector', $pixels = 10); // Or to the right if you're feelin' frisky
$browser->dragUp('.selector', $pixels = 10); // Time to go up, up and away!
$browser->dragDown('.selector', $pixels = 10); // Or down, down, deeper in the code!
Now, if youโre looking to move your element by a certain offset instead of a fixed direction, letโs give it a little x and y nudge:
$browser->dragOffset('.selector', $x = 10, $y = 10); // X marks the spot, Y navigates the way!
Saddle up, partner! Itโs time to start wrangling those elements like a true frontier hero!
Alrighty then! Letโs dive into the world of JavaScript Dialogs, where pop-ups and prompts reign supreme. Dusk, our trusty sidekick, is here to help us tame these digital beasts.
First off, ever been stuck waiting for a dialog to load faster than a cheetah on caffeine? Fear not! With waitForDialog method, you can specify up to how many seconds (or even minutes if youโre that patient) Dusk should wait for thedialog to make its grand entrance.
$browser->waitForDialog($seconds = null); // In case you've nothing better to do
Next, letโs talk assertions. Remember when your parents asked you to prove that you actually did your homework? Well, the assertDialogOpened method does something similar but for dialogs. It ensures that a dialog has appeared on screen and carries the message you specify:
$browser->assertDialogOpened('Dialog message'); // Makes sure Mom doesn't find out about those late nights playing video games
If your JavaScript dialog is a chatty one, eager to hear your side, you can use the typeInDialog method. Itโs like sending a text to that pesky telemarketer, but with more style:
$browser->typeInDialog('Hello World'); // Remember to keep it casual and friendly
Now, letโs say youโve got the dialogโs attention and want to close it. The โOKโ button is your best bet? No problem! Simply invoke the acceptDialog method:
$browser->acceptDialog(); // Closes the dialog without causing a scene
But what if you changed your mind? No worries! If you want to dismiss the dialog by clicking โCancelโ, the dismissDialog method has got your back:
$browser->dismissDialog(); // Makes a hasty exit, just in case things aren't going as planned
Now that weโve covered the basics, itโs time to explore more! Happy coding, and may your dialog interactions be as smooth as a well-oiled robot. ๐ค๐
Navigating the Matrix of Frames (I mean, iframes)
If youโve found yourself in a pickle with elements trapped within the matrix of an iframe, fear not! Weโve got the withinFrame method to save the day. This superhero swoops in and lets you perform all sorts of magical interactions, but only within the confines of the chosen iframe:
$browser->donTheCape('#credit-card-details', function ($browser) {
$browser->keyboardNinja('input[name="cardnumber"]', '4242424242424242')
->keyboardNinja('input[name="exp-date"]', '1224')
->keyboardNinja('input[name="cvc"]', '123')
->clickButton('Pay');
});
Now, you might be wondering about the selection process inside this mystical realm. Fear not, for our methodโs got your back! Selector scoping is automatically applied to match only the elements within the specified iframe, just like a magic spell that focuses its power on the right targets. So go ahead and let loose your inner superhero in the world of iframes!
Scope Creep Control
Sometimes you might find yourself juggling multiple tasks while ensuring each task is confined to a specific selector. Picture it like orchestrating a symphony, where every instrument (operation) plays its part only within the designated section (selector). Laravelโs with method is your baton conductor for this performance!
$orchestra->with('.table', function ($table) {
$table->assertHears('Hello World') // You can replace "hears" with "see", it's showbiz
->tapDanceLink('Delete'); // A fancy way of saying 'clickLink'
});
Occasionally, you might need to step outside the current spotlight and perform assertions away from your designated section. Donโt worry; the elsewhere and elsewhereWhenAvailable methods are your stagehands backstage, ready to help!
$orchestra->with('.table', function ($table) {
// Current set: body .table...
$orchestra->offStage('.page-title', function ($title) {
// Current set: body .page-title...
$title->assertHears('Hello World');
});
$orchestra->offStageWhenReady('.page-title', function ($title) {
// Current set: body .page-title...
$title->assertHears('Hello World');
});
});
Now, remember to avoid stage freight and wait patiently for elements to be ready with the waitFor method!
$orchestra->with('.table', function ($table) {
// Wait for the table and its contents to appear...
$table->waitFor();
// Continue your performance...
});
Ahoy there, testing pirates! With JavaScript-laden shipwrecks aplenty in the vast sea of apps, itโs a common scurvy issue to find yourself in need of a spot oโ patience before diving into a test. But fret ye not, for Dusk has ye covered with its nifty โwaitingโ feature!
The Patience Potion
When it comes to testing apps that make your hair curl with JS, waiting is often the name of the game. But donโt let it drag you down, Dusk will make you feel like a seasoned sailor navigating through the Bermuda Triangle! With an arsenal of methods at your disposal, you can wait for elements to magically appear on the page or even be as patient as a saint till a JavaScript expression transforms into a jolly โtrueโ pirate.
Now that ye know what awaits you, letโs hoist the sails and set sail towards these waiting methods! Yarr! ๐ดโโ ๏ธ ๐ข
Remember: Patience is a virtueโand in the world of testing with Dusk, itโs also a vital skill!
Alrighty, letโs get this test fiesta started! If you find yourself needing a time-out (the breakdancing kind is not supported here), use the pause method to put your tests on hold for a specified number of milliseconds:
$browser->pause(1000); // That's 1 whole second, buddy!
But what if you want your test to take a breather only when certain conditions are met? Well, thatโs where the pauseIf method comes in handy:
$browser->pauseIf(App::environment('production'), 1000); // Only pause if we're in production mode, 'cause who needs speed there, right?
Now, what if you want your test to keep going unless some conditions are met? Fear not, for the pauseUnless method is here to save the day:
$browser->pauseUnless(App::environment('testing'), 1000); // Don't pause in testing mode - we've got a lot of tests to run!
Just remember, these methods are like the traffic cops of your tests, ensuring they donโt move too quickly or get stuck in the wrong place. Happy testing, and remember: in Laravel, timing is everything! ๐ฐ๏ธ๐ฅ๐
Ahoy there, Laravel coders! Letโs embark on an exhilarating journey through the vast seas of testing with Laravelโs waitFor method. This nautical navigator can halt your testโs voyage until a specific CSS or Dusk selector sets sail on your web page.
By default, it waits bravely for five seconds before hoisting the Jolly Roger and throwing an exception if the pirate-hunting treasure isnโt found. But you can set a custom timeout threshold as the second mate would say: โYarr, make that one second instead!โ
// Ahoy! Wait up to five seconds for ol' 'selector'.
$browser->waitFor('.selector');
// Hold your horses! Let's wait just one second for ol' 'selector' instead.
$browser->waitFor('.selector', 1);
Now, if youโre searching for a specific text hidden within that treasure chest, the waitForTextIn method is your compass. It can help you sail the waters until your desired text emerges.
// Set sail for five seaside minutes, looking for "Hello World".
$browser->waitForTextIn('.selector', 'Hello World');
// Hurry up, matey! Let's wait just one nautical minute for "Hello World" instead.
$browser->waitForTextIn('.selector', 'Hello World', 1);
If you find yourself needing to check if the treasure has disappeared or if itโs hidden behind a cursed fog, use the waitUntilMissing method:
// Wait up to five seaside minutes until ol' 'selector' disappears.
$browser->waitUntilMissing('.selector');
// Hurry up, matey! Let's wait just one nautical minute until "selector" is gone instead.
$browser->waitUntilMissing('.selector', 1);
Lastly, if youโre curious about the status of your treasure chest (whether itโs locked or unlocked), use waitUntilEnabled and waitUntilDisabled to get a feel for its current state.
// Wait up to five seaside minutes until ol' 'selector' is unlocked.
$browser->waitUntilEnabled('.selector');
// Hurry up, matey! Let's wait just one nautical minute until "selector" is unlocked instead.
$browser->waitUntilEnabled('.selector', 1);
// Wait up to five seaside minutes until ol' 'selector' is locked.
$browser->waitUntilDisabled('.selector');
// Hurry up, matey! Let's wait just one nautical minute until "selector" is locked instead.
$browser->waitUntilDisabled('.selector', 1);
Avast there, happy sailing and may your tests always be successful voyages! ๐ด๐๐ดโโ ๏ธ
Ah, the magical world of Laravel testing! Where elements dance to our commands and modal windows waltz at our beck and call. But alas, we donโt always get the chance to twirl them as soon as they appear on stage. Enter the charming whenAvailable method! This dashing gentleman is your wingman when you want to wait for a suave selector to show up, then sweep it off its feet with some delightful interactions.
For instance, imagine youโre at a digital ball and see a striking modal window making its entrance. But oh, the nerve! It wonโt let you press that dashing โOKโ button until you ask politely. No worries, just summon whenAvailable to make your move:
$browser->whenAvailable('.modal', function (Browser $modal) {
$modal->assertSee('Hello World')
->press('OK');
});
And there you have it! Your dapper browser is now ready to charm the modal, making sure it sees the correct โHello Worldโ before pressing its โOKโ button with a dash of elegance. So go forth and test, dear developers, for this method will make your tests as smoooth as silk. ๐คณ๐
Alright, buckle up, code cowboys and codettes! Letโs dive into the wild west of web scraping with Laravelโs trusty waitForText sheriff. This here method is your new best friend when youโre patiently (or not so patiently) waiting for a specific text to appear on your digital frontier:
// Give ol' '5 seconds to see "Hello World" pop up on the page:
$browser->waitForText('Hello World');
// If you're just itchin' for a quick draw, wait only a single second:
$browser->waitForText('Hello World', 1);
But what about when youโve had enough of that text and itโs time to say goodbye? Well, the waitUntilMissingText is your trusty deputy. Use it to wait for your unwanted text to vanish:
// Give "Hello World" a maximum of five seconds to high-tail it outta there:
$browser->waitUntilMissingText('Hello World');
// If you can't wait that long, catch it in just one second:
$browser->waitUntilMissingText('Hello World', 1);
So there ya have it, pardner! Now you can wrangle those pesky texts like a pro with Laravelโs waitForText and waitUntilMissingText. Happy web scraping!
Ahoy there, intrepid Laravel explorers! If youโve ever found yourself in a pickle, waiting for a link to magically appear on your web page like Cinderellaโs carriage at the stroke of midnight, fear not! For we have just the method to tickle your fancy and rescue you from such predicaments - itโs called waitForLink!
This enchanting little helper will ensure you donโt miss a beat while youโre eagerly awaiting your beloved link text to dance onto the stage. Give it a whirl, and watch as your waiting woes float away on a breeze:
// Set sail for the land of patience, where links come to play...
$browser->waitForLink('Create'); // ...for up to five whole seconds!
// Or if you're feeling particularly impatient...
$browser->waitForLink('Create', 1); // ...you can try a one-second voyage instead!
Fair winds and following seas, dear coders! May this magical method bring you closer to your linky goals and help you conquer the wild frontier of web development. Hurrah!
Ahoy there, code cowboys and codettes! Letโs talk about a lilโ wrangler named waitForInput. This olโ method is just the sheriff you need to keep your page in line when it comes to inputs.
You see, sometimes your page gets all scatterbrained and forgets to show up for workโer, an input field. Well, this cowpoke wonโt stand for that kind of shenanigans! Heโll make sure that input shows its face or you wait a maximum of five seconds (in case itโs just being shy).
// Give 'em the old five-second stare...
$browser->waitForInput($field);
But if youโre in a hurry, this olโ wrangler can also make sure the input appears in a flash (one second to be precise).
// Speed things up!
$browser->waitForInput($field, 1);
So saddle up and wrangle those inputs like a pro, partner! Donโt let your page get away with being lazy. Keep them on their toes, or youโll find yourself herding cats instead of data!
Ahoy there, code swashbucklers! Sailing the seas of Laravelโs TestDomen, you might have come across a situation where Captain $browser is shouting โLand ho!โ but his compass is spinning wildly. Fear not, dear matey! This here be a problem of asynchronous window.location.pathname updates.
To keep your bearings straight, use the trusty olโ waitForLocation method. Just like youโd wait for the perfect storm to pass before setting sail, you can wait for the location to reach your desired destination:
$browser->waitForLocation('/secret'); // Waits for the browser to land on the secret island
If you want to make sure that Captain $browser has reached a fully-qualified URL, just give it a specific URL anchor:
$browser->waitForLocation('https://example.com/path'); // Waits for the browser to reach example.com/path with all its sails set
But what if youโre trying to find a particular landmark, like a named route? Fear not, my friend! Just drop the waitForRoute anchor:
$browser->waitForRoute($routeName, $parameters); // Waits for the browser to dock at the specified named route
So there you have it, mateys! Use these methods wisely, and soon enough, Captain $browser will be shouting โLand ahoy!โ with a smile on his face, instead of spinning wildly in confusion. Now letโs set sail for more adventures in Laravel TestDomen! Arrrr! ๐ดโโ ๏ธโ๏ธ
Ahoy, code pirates! Sail with me through the treacherous seas of Laravel Dusk, where the quest for speed and precision is never-ending!
Navigating Page Reloads like a Pro!
Got a page thatโs taking its sweet time to reload after an action? No worries, matey! Just call upon the mighty waitForReload method:
use Laravel\Dusk\Browser;
$browser->waitForReload(function (Browser $browser) {
$browser->press('Submit');
})
->assertSee('Success!');
Now, if you find yourself repeatedly clicking that darn button and waiting for the page to reload, fear not! The clickAndWaitForReload method has been dispatched to make your life a whole lot easier:
$browser->clickAndWaitForReload('.selector')
->assertSee('something');
Oh, and donโt forget about those pesky JavaScript expressions that could hold up your treasure hunt! Keep them at bay with the waitForJavascript method:
$browser->waitForJavascript('myElement', function () {
// Your code here
})->assertSee('Gold, glorious gold!');
Smooth sailing, my friends! May your code always be swift and your treasure abundant! ๐ด๐ดโโ ๏ธ
Alrighty, letโs tango with JavaScript expressions without breaking a sweat (or your code)! Sometimes you might find yourself in a pickle, eager to halt the test dance until a certain JS expression becomes as true as Bigfoot sightings. Fear not, my friend! The waitUntil method is here to save the day!
Without further ado, letโs get this party started. Ponder upon the following examples:
// Wait up to five seconds for Bigfoot to show up in App.data.servers array...
$browser->waitUntil('App.data.servers.length > 0');
// For those with a short attention span, wait just one second for Sasquatch to appear...
$browser->waitUntil('App.data.servers.length > 0', 1);
Just remember, no need to include the return keyword or an ending semi-colon in your expression when using waitUntil. Weโre all about making coding as simple as ordering a pizza! Enjoy the dance! ๐บ๐ผ๐๐ผ
Alright, buckle up, code cowboys and codettes! Weโre about to embark on an exhilarating journey into the wild west of Laravel testing, where Vue components are our tumbleweeds and JavaScript events are our stagecoaches. Letโs talk about those trusty olโ waitUntilVue and waitUntilVueIsNot methods.
These ainโt your average cowpoke tools; theyโre the sheriffs that keep an eye on your Vue component attributes, ensuring theyโve got the right value in townโor elsewhere in those HTML badlands!
// Want to wait until ol' 'user.name' hollers "Taylor"? Saddle up and ride this line of code:
$browser->waitUntilVue('user.name', 'Taylor', '@user');
// Now, suppose you want to find out when 'user.name' ain't got no value at allโlike a horse with a missing brand. That's where `waitUntilVueIsNot` steps in:
$browser->waitUntilVueIsNot('user.name', null, '@user');
Just remember, these trusty sidekicks are here to help you wrangle those Vue components and keep your Laravel tests on track! Yee-haw!
Alright, letโs dive into the world of Laravelโs testable charm! When youโre not sure how to keep your tests entertained until the JavaScript party starts, fear not! The waitForEvent method is here to save the day.
Think of it as the bouncer at a club, making sure your test doesnโt leave before the disco ball starts spinning:
$browser->waitForEvent('load'); // Cue the music and let the dance begin!
By default, our friendly bouncer is stationed at the entrance of the body element, but if youโve got a scoped selector, heโll happily move to the matching dance floor:
$browser->with('iframe', function (Browser $iframe) {
// Ask the bouncer to move to the iframe's dance floor...
$iframe->waitForEvent('load');
});
And, just like a hip hop DJ, you can even ask our bouncer to play on a specific element:
$browser->waitForEvent('load', '.selector'); // Let's get selective!
But wait, thereโs more! Our bouncer can also handle events happening at the big stage (the document and window objects):
// The crowd is on their feet, waiting for the DJ to scroll...
$browser->waitForEvent('scroll', 'document');
// Give the party-goers five seconds to resize their windows...
$browser->waitForEvent('resize', 'window', 5);
Now you can keep your tests dancing all night long without having to worry about them leaving too soon! Keep on testing, and remember, itโs always a party with Laravel! ๐๐๐บ
The Dance of Delay and Decision with Callback Captain Dusk! ๐บ๏ธ๐ซ
Ahoy, mateys! Buckle up for a thrilling journey into the heart of Laravelโs Dusk, the swashbuckling testing companion that every pirate needs! Many of our โwaitโ methods are powered by a secret ally called waitUsing. Fancy meeting you here, old chum! You can summon it directly to keep watch over a particular closure, making sure it returns a hearty โaye-aye captain!โ before raising the anchor. The waitUsing method is as loyal as a parrot on your shoulder and as flexible as a pirateโs cutlass:
$browser->setSailsAblaze(10, 1, function () use ($something) {
return $something->isReady(); // Ahoy! Check if it be ready to go!
}, "Arrrgh! Something be not shipshape in time!");
Pirate Speak Translation:
$browser->waitUsing(10, 1, function () use ($something) {
return $something->isReady();
}, "Something wasn't ready in time.");
Scrubbing the Decks: Scroll an Element into View ๐งน๐ฌ
Mateys, sometimes, you need to focus on a particular element to make sure your tests donโt get lost at sea. Fear not, for our trusty first mate, scrollIntoView, is always ready to help! It can scroll an element into view with just a few simple commands:
$element->squintAt($browser); // Give the element a good squinting, matey
$browser->focusOn($element); // Get ready to take aim, ye scurvy dog!
$element->comeIntoView(); // Ahoy there! Pop into view for a proper looksee
Pirate Speak Translation:
$element->scrollIntoView($browser);
So hoist the Jolly Roger, me hearties! Laravelโs Dusk is here to make your adventures on the seas of testing a right barrel of fun and excitement! Yarr! ๐ดโโ ๏ธโจ
Unleashing the Ninja Scroll Master!
Ever found yourself reaching for an element only to discover itโs a sneaky ninja hiding off-screen? No worries, Laravelโs here to save the day with our secret ninja scroll technique!
Introducing: The scrollIntoView method - your digital sensei that will guide the browser window to roll, tumble, and flip until your selected element (identified by a crafty .selector) appears before your eyes like a ninja star in the spotlight.
$browser->ninjaRoll('scroll', '.selector')
->clutchClick('.selector');
Now thatโs some high-level browsing action right there! ๐ฏ
Ah, the delightful world of Dusk assertions! This Laravel package is chock-full of helpful methods for checking your applicationโs behavior. Letโs dive in and tickle your fancy with a smorgasbord of assertion goodness:
- assertTitle: Does your page have the correct title? Letโs verify!
- assertTitleContains: Is your pageโs title a part of the fun? Find out with this assertion!
- assertUrlIs: Did you navigate to the right URL? Time to check if all links are in order!
- assertSchemeIs: Is your application using HTTPS, like a modern gentleman? Letโs confirm!
- assertHostIs: Did you land on the correct host? Time to check if youโre in the right place!
- assertPathBeginsWith: Does your path start as planned? Letโs find out if itโs a match made in heaven!
- assertPathEndsWith: Did your path reach its destination? Time to check if the journey was successful!
- assertPathContains: Is your path hiding something? Letโs look for it and make sure itโs there!
- assertPathIsNot: Did you end up somewhere unexpected? Weโll help you confirm if you took a wrong turn!
- โฆand many more assertions to come! This is just the beginning of your testing adventure with Dusk! ๐๐ค๐
Ahoy there, web wranglers! Letโs dive into a bit of Laravel enchantment we like to call assertTitle. This oneโs a charm for ensuring your pageโs title is not just any old fishermanโs yarn, but the precise, well-spun tale you intended it to be.
$browser->assertTitle($title);
Just replace $title with the title text your little heart desires - after all, a misnamed page is worse than a cat calling itself a fish! If your pageโs title isnโt matching up like peanut butter and jelly, this spell will let you know pronto.
Now, donโt be all sea legs when it comes to navigating to other parts of the docs โ if youโre looking for assertTitleContains, you can find that here:
โNavigate here for a more permissive page title check, where the given text appears anywhere in your title!โ (Wink wink) ๐
Ahoy there, intrepid Laravel voyagers! If you find yourself in need of verifying that a pageโs title is as scintillating as your favorite pirateโs parrot, then look no further than assertTitleContains! This dashing little function will ensure the page title has the specified text, or risk walking the plank of error handling.
Simply cast your spell upon it like so:
$browser->assertTitleContains($title);
Just remember, a stitch in time saves nine, and a good title check saves you from a world of confusion! May your code be swashbucklingly successful!
Ahoy there, code pirates! Letโs set sail through the vast seas of Laravel land and learn about our trusty friend assertUrlIs(). This be a handy function that checks if Captain Current URL (query string be gone) matches with the swashbuckling string you provide.
So, suppose ye want to ensure that your boat is anchored at https://www.treasureisland.com, you can use this magical spell:
$browser->assertUrlIs('https://www.treasureisland.com');
Just remember, this function only checks the URL without its query string โ so donโt worry about those treasure map coordinates muddying the waters! ๐
Now that ye know how to keep your ship on course with assertUrlIs(), itโs time to set sail and conquer more Laravel treasures! Arr matey, happy coding!
Ahoy there, coding pirates! Set sail on an adventure filled with web pages and the magic of Laravel!
Fasten your eyepatches and prepare to embark upon a quest as thrilling as finding Captain Blackbeardโs buried treasure: letโs learn about the assertSchemeIs function. Arrr matey!
This humble yet powerful function is here to ensure that the current URL scheme matches the one you provide, like the shrewd navigator it is. So hoist the anchor, steer the ship right, and unleash your inner Captain Hook:
$browser->assertSchemeIs($scheme);
Now, if youโre sailing through a different scheme, donโt worry, matey. We got yer back with assertSchemeIsNot. Just follow the compass and set it to your desired scheme:
$browser->assertSchemeIsNot($scheme);
Now, remember this one - it could be as useful as a trusty parrot on your shoulder when navigating the web seas! Happy coding and may all your assertions come true!
Ahoy there, Laravelers! Letโs set sail into the world of testing with a splash of humor. Today weโre diving deep into the enchanting assertSchemeIsNot function, which is like the web development worldโs equivalent of telling your overzealous friend that no, you donโt want to go skydiving without a parachute!
So what exactly does this piratey little snippet do? Well, it checks whether the current URL scheme (http, https, or whatever floats your boat) is not the scheme you specify. Think of it as your trusty compass that tells you when youโre on the wrong side of the internet seas!
Hereโs an example of how to use it:
$browser->assertSchemeIsNot('https'); // Ensures we're not browsing secret agent websites
By employing this function in your tests, youโll be able to navigate the murky waters of web development with greater confidence and less fear of stumbling upon unwanted destinations. Just remember, with great power comes great responsibilityโso donโt go testing sensitive areas without a proper disguise! Happy sailing! ๐โ๏ธ
Ahoy there, code pirates! Sail into the winds of Laravel land with me as we set sail on a journey to learn about assertHostIs. Itโs not just a fancy word that sounds like it belongs in a Tolkien novel; itโs a powerful function that ensures your URL host is as tame and obedient as a well-trained parrot.
So, what does this magical spell do, ye ask? Simple, really! It checks if the host of the current web page matches the one youโve provided like a ship matching its true coordinates. Hereโs how it works:
$browser->assertHostIs($host);
In this code, $browser is your trusty steed, and $host is the landmark you want to reach on your web voyage. Just replace $host with the desired destination (be it www.treasureisland.com or www.shipwreck.net), and Laravel will let you know if youโve docked at the right harbor.
Now, why would ye need such a function? Picture this: Youโre testing a web application, and you want to ensure that it takes users to the correct page when they click on specific links. assertHostIs is your trusty sidekick in this quest, making sure the pirate ship of your app doesnโt sail off course!
So, hoist the mainsail and set a course for better testing with assertHostIs. Arrr matey, Laravel makes coding as fun as sailing on a treasure hunt!
Ahoy there, code swashbucklers! Letโs sail into the world of Laravel testing with a hearty โArrrโ, shall we? First stop: assertHostIsNot!
This particular function is like the pirateโs parrot on your shoulder, warning you when things ainโt right. Its job is to ensure that the current URL host is not the one youโve specified like a good old-fashioned sea shanty.
$browser->assertHostIsNot($host);
Imagine yourself on the high seas, and your ship somehow ended up in Port Royal instead of Port Royal, Nevada! Thatโs what this function is here to prevent โ a Laravel test shipwreck before it even starts. Keep testing those waters, mateys!
Alright, letโs dive into the world of Laravel URL port detective work! ๐ต๏ธโโ๏ธ๐
Youโve got a hunch that the current webpage youโre browsing is playing host to some secret shenanigans on a mysterious port? Well, fear not, my friend! Laravel has got your back with the assertPortIs() function. ๐ฆธโโ๏ธ
Hereโs how to put it to good use:
$browser->assertPortIs($port);
In plain English, this means that Laravel will take one look at the URL youโre currently visiting and check if itโs as naughty or as nice as the port number you provide. If they match up like peanut butter and jelly, then congrats! Your webpageโs port behavior is all above board. ๐ฅ๐ฐ
But hey, if your suspect doesnโt play by the rules, donโt worry! You can also use assertPortIsNot() to double-check that your URL isnโt hiding anything fishy on a different port. Itโs like having your very own digital lie detector test. ๐ต๏ธโโ๏ธ๐ฎโโ๏ธ
So go ahead, uncover the hidden secrets of the web one Laravel function at a time! ๐๐ต๏ธโโ๏ธ
Oh, the suspense is real! Letโs dive into Laravelโs playful side and discuss the enigmatic assertPortIsNot function. Imagine youโre a detective on a mission to uncover a port mismatch mystery. Hereโs your trusty tool to crack the case:
$browser->assertPortIsNot($port);
In this exciting scenario, you play the role of a determined investigator trying to figure out if the current URL port is definitely not the one you suspect. Use this function like Sherlock would use his magnifying glass, and watch as it reveals whether your hunch about that elusive port number was correct or not!
Now, donโt forget to keep those detective gears turning, because there are plenty more investigations ahead in Laravel Land! ๐ต๏ธโโ๏ธ๐๐
Ahoy there, coding seafarers! Today weโre diving into a swashbuckling adventure with Laravelโs assertPathBeginsWith. This isnโt your average pirate treasure map, but it sure can help you navigate the web like a seasoned sailor!
Ever found yourself lost in cyberspace, wondering where on earth (or rather, URL) you are? Worry no more, matey! With assertPathBeginsWith, you can ensure your current URL path starts off exactly as expected. No need for squinting at maps and compasses - just a simple line of code will do the trick:
$browser->assertPathBeginsWith('/home');
Say youโre visiting www.example.com/home/about, and your heart yearns for /home. Just fire up this command, and Laravel will raise the Jolly Roger if it spots anything but a beginninโ with โ/homeโ. Arr matey, thatโs one way to keep your web app on course!
Ahoy there, code cowboys and codettes! Today, weโre diving into a Laravel gem so shiny it makes unicorns jealous - the assertPathEndsWith. This isnโt your garden-variety assertion function; itโs more like the snobby relative at family gatherings who knows exactly where the silverware goes.
But instead of judging your table manners, it checks if your URL path is as proper as your great auntโs Christmas fruitcake. Hereโs how you can use it:
$browser->assertPathEndsWith('/home');
Imagine youโre in a game of Guess the URL Ending, and /home is the answer. The browser will then confirm if your current path has been hitting all the right notes to end with that sweet, sweet /home. If it matches, congratulations! Youโve won the game and saved yourself from serving a fruitcake for dessert. But remember, just like with family, you might want to check multiple paths before you can be sure youโre on the right URL street.
Happy coding, pioneers! May your URLs always end in style.
Ahoy there, intrepid Laravel adventurer! Letโs dive right in and talk shop about the swashbuckling assertPathContains function.
This here piratey piece of code is your trusty sidekick when it comes to verifying that the URL path youโre currently navigating has a specific treasure map โ I mean, path โ hidden within it.
$browser->assertPathContains('/home');
Imagine this as the old captain himself, squinting at the horizon and exclaiming, โArr matey! Check the url, be sure itโs got that island we be lookinโ for!โ
In other words, when you fire up assertPathContains, itโll make sure your URL has a piece of the path thatโs as sweet as grog and as essential as ye olde parrot. So keep on sailing through your tests, with this handy mate aboard! ๐ดโโ ๏ธ๐๐ฆ
Oh, the โassertPathIsโ function! Itโs like a digital version of your nosy neighbor who canโt help but peer over your virtual fence to see if youโre on the right path - without actually invading your privacy (promise).
Just drop this snippet into your code:
$browser->assertPathIs('/home');
This little gem will check if our browserโs current URL location is exactly like the one provided (in this case, โ/homeโ). If it is, everythingโs dandy. But if not, wellโฆ letโs just say they might need a GPS upgrade! ๐
Ahoy there, fearless PHP adventurers! Letโs take a larrikin journey into Laravelโs enchanted realm and explore the mystical assertPathIsNot. ๐ฉ๐งโโ๏ธ
Ready to set sail? First mate, buckle up as we plunge headfirst into the digital abyss of URLs. You know, itโs like going down the rabbit hole, but instead of a curious Alice, we have a hungry browser barreling through the web! ๐ฐ๐ช๏ธ
So, whatโs this assertPathIsNot all about? Well, itโs our trusty pirate compass to make sure we ainโt ended up on some sketchy shore, like the one named โ/homeโ. Itโs as simple as this:
$browser->assertPathIsNot('/home');
Now, you might be wondering, โMatey, why on earth would I ever want to avoid a place called โhomeโ?โ Well, there could be all sorts of reasons! Perhaps weโre searching for buried treasure in the wilds of โ/treasure-chestโ, but we donโt want to end up in the dull doldrums of โ/homeโ.
And hey, remember, when youโre navigating the vast seas of the internet with Laravel, it pays to keep an eye out for potential shipwrecks! Happy coding and may your browser never meet its Waterloo on a treacherous โ/homeโ! ๐๏ธ๐ณ๏ธ๐
Ahoy there, intrepid Laravel wranglers! Fancy a bit of PHP fun? Well, grab your cowboy boots and letโs gallop into the world of assertRouteIs!
Saddle up with assertRouteIs!
Ever found yourself lost in the wild west of URLs, yearning for some order? Worry not! assertRouteIs is here to tame that tangled mess!
$browser->lassoTheURL($name, $parameters); // Yes, we're being a bit dramatic... but it's more fun!
What on earth am I talking about? Simply put, assertRouteIs is your faithful steed that asserts the current URL matches the given named routeโs URL. Thatโs right, it keeps your routes in line and wrangles them like a seasoned cowboy!
Now, if you fancy a challenge, assertRouteIs even lets you pass parameters to ensure the match is a perfect one. Itโs like a gunslinger who can pick out the outlaws among the masses with pinpoint accuracy!
$browser->lassoTheURL($name, [
'id' => 123,
'username' => 'buckaroo', // Just rollin' with this cowboy theme!
]);
So grab your six-shooters, hop aboard assertRouteIs, and letโs ride into the sunset of bug-free code together! Yee-haw!
The Magical Query String Verifier
Ready to pull some digital rabbits out of your hat? Introducing the Query String Wizard! This enchanting spell will ensure that your given query string parameter is as present as a cat on a hot tin roof.
$browser->castMagic('QueryStringPresence', $name); // Just like 'Harry Potter and the Chamber of Secrets'
Feeling extra mystical? Want to make sure your query string parameter isnโt just present but also has a specific value, like finding a four-leaf clover in a field full of three-leaf clovers? No problemo!
$browser->castMagic('QueryStringValueMatch', [$name, $value]); // Just like 'Harry Potter and the Prisoner of Azkaban' when he finds out Sirius is a werewolf
If youโre feeling skeptical about your query strings, give this spell a whirl. Itโs as reliable as a Britney Spears comeback! ๐ถ๐
Alright, letโs dive into the quirks of Laravelโs query string! Ever found yourself in a pickle because you canโt find your beloved ?bananagram=420 in the URL soup? Well, fear not! We have just the tool to tickle your troubles away.
Introducing assertQueryStringMissing($name), the super sleuth that helps you track down missing query string parameters like a digital Sherlock Holmes (minus the cocaine and violin). If the specified parameter is nowhere to be found in your query string, this function will cheerfully let you know with an assertion, thus saving you from endless scrolling.
So next time youโre having a whodunit moment with your URL, remember to call upon assertQueryStringMissing($name). Itโs the perfect wingman for those times when your URL feels like itโs playing hide and seek with you!
Oh, hello there! Letโs dive into the world of Laravel testing with a splash of humor. Today weโre chatting about assertFragmentIs, which is like the bouncer at the coolest club in town, checking if your URLโs hash fragment matches the VIP list (er, given fragment).
So, imagine youโve got yourself a URL that looks something like this: https://awesomesite.com/#anchor. Well, our friendly neighborhood bouncer, aka assertFragmentIs, would be happy to check if โ#anchorโ is on the list (er, matches the given fragment).
Hereโs how you can invite him over for a dance:
$browser->assertFragmentIs('anchor');
Now isnโt that just swell? Enjoy your time with our witty bouncer! Remember, heโs always ready to check if the hash fragments of your URLs match their respective VIP guests. Cheers! ๐ฅณ๐๐๐บ๏ธ
Ahoy there, coder! Letโs dive into a fun little Laravel function that goes by the name of assertFragmentBeginsWith. This clever chap is here to ensure your URLโs party-loving hash fragment starts with a specific guestlist (er, fragment). Just imagine, youโre hosting a digital soiree and you want to make sure only cool kids named โanchorโ are invited. Hereโs how to put this function to work:
$browser->assertFragmentBeginsWith('anchor');
Now, if for some bizarre reason your URL decides to invite a Johnny-come-lately with a hash fragment starting anywhere but โanchorโ, youโll be notified faster than you can say โparty foul!โ This function plays the role of the party pooper, but in the best way possible โ by keeping your code clean and tidy.
And thatโs not all! If you feel like being even more discerning about who makes the guestlist, thereโs also assertFragmentIsNot waiting in the wings to ensure no gatecrashers ruin your bash. Just remember, a little party supervision can save you from an unwanted headache. So go forth and code with confidence! ๐๐๐ฅณ
Alright, hereโs your dose of geek humor for the day! Letโs delve into Laravelโs assertFragmentIsNot, shall we?
Imagine youโre hosting a virtual tea party with all your HTML friends (tags), and youโve invited them to gather โround the anchor link (#). Now, the last thing you want is an uninvited guest crashing your party! Thatโs where our beloved assertFragmentIsNot comes into play.
$browser->assertFragmentIsNot('anchor');
In simpler terms, this line of code is like putting up a bouncer for your webpage. It checks if the current hash fragment (the uninvited guest) doesnโt match the one you specified (โanchorโ). If the wrong link shows up at your virtual doorstep, this function will call out and throw an error, ensuring that only your invited HTML friends get to party! ๐๐
Now, if you find yourself in a situation where you do want to check for a specific anchor link, Laravelโs got you covered with the assertFragment function. It works like a guest list checker, making sure that the uninvited guests are kept at bay and your tea party stays classy! ๐ต๐ค
Hope this little tutorial brought a smile to your face while also helping you understand Laravelโs functionalities better. Happy coding, and may all your webpages be tea-party-approved! ๐๐๐ฐ
Ahoy there, coding cowboy! Letโs dive into a little chocolate chip cookie detective work โ Laravel style! ๐ช๐ต๏ธโโ๏ธ
You know those encrypted cookies youโve been stashing away like a squirrel hoarding acorns? Weโre about to make sure theyโre not missing in action! Hereโs how:
$browser->assertHasCookie($name);
This right here is the cookie-dusting tool you need. Just give it the name of your little friend, and it will check if itโs mingling with all the other cookies in the jar (your userโs session). If that crafty rascal has gone AWOL, this function will let out a mighty roar loud enough for the whole server to hear.
So go ahead, sleuth around, and make sure your cookies are always accounted for! ๐ต๏ธโโ๏ธ๐ช
Ahoy there, Captain Cookie! Sailors of the digital realm, listen up! If youโve found yourself in a pickle trying to verify if your humble ship (website) is carrying a specific, unencrypted cookie (letโs call it โCapโn Crumblesโ), fret not! Laravel has crafted a trusty pirate tool just for this nautical endeavor.
Wield the mighty assertHasPlainCookie() like a cutlass! Hereโs how to use it:
$browser->assertHasPlainCookie($name);
Imagine if Captain Crumbles was your loyal parrot, and you wanted to confirm heโs safely perched on your shoulder (your website)! This function is the sextant you need to avoid shipwrecking into a cookie-less ocean.
If, for some unlucky reason, Capโn Crumbles has flown the coop (gone missing), Laravel will raise an alarm with a friendly reminder that your website lacks the specified cookie. You can then set sail to bake more Capโn Crumbles and serve them up to your loyal visitors. Yarr! Happy baking, mateys! ๐ชโ ๏ธ๐
Ahoy there, code pirates! Sail the seas of cookies with us as we delve into the swashbuckling world of Laravelโs assertCookieMissing().
Yarr, this gem of a function is here to ensure that your precious encrypted cookie isnโt lurking around like a sneaky barnacle on your ship.
To get started, grab your favorite parrot and fire up those keels! Hereโs how yeโll use assertCookieMissing():
$browser->assertCookieMissing($name);
So if ye be looking for a way to make sure your treasure map cookie ainโt been planted by scurvy knaves, this be the function for you!
assertCookiesAinโtGotNoAlibi, Mate!
Get ready to play detective with this Laravel gem! Investigate your website like a modern-day Sherlock Holmes and ensure that the suspect cookie youโve named $name isnโt hanging around uninvited. Hereโs how to do it:
$browser->assertCookiesAin'tGotNoAlibiMate($name);
In this exciting game of โWho Cooked My Cookie?โ, Laravel will check if the unencrypted cookie with the specified name doesnโt exist in the cookie jar. If it does, prepare for a shocking twist, because your uninvited guest is still lurking!
Ahoy there! Sailors of the digital seas! Meet assertCookieValue, your new favorite sailorโs mate on this Laravel ship!
This here function will help you ensure that a hidden treasure (aka encrypted cookie) in your browserโs hold has a specific value:
$browser->assertCookieValue($name, $value);
If Captain Cookies (your browser) is found to be harboring a different pirate loot than what you expect, this mate will hoist the distress flag! Just like a good mate should. Now, isnโt that swashbucklingly awesome? Sail safe, mates! ๐ดโโ ๏ธ ๐
Ahoy there, code wranglers! If youโre in need of ensuring your unencrypted cookie is as faithful to its intended value as a golden retriever is to fetching its favorite ball, then look no further!
Enter the stage: assertPlainCookieValue, the trusty ally thatโll help you keep your digital cookies crisp and accurate.
Hereโs how it works:
$browser->assertPlainCookieValue($name, $value);
In this sweet symphony of PHP, replace $name with the name of your scrumptious cookie (e.g., โcookieNameโ). As for $value, thatโs where you specify the value your heart desires (e.g., โthe secret ingredient to the perfect chocolate chip recipeโ).
So, if youโre tired of feeling like the cookie monster searching for his elusive missing treats, give this fine function a whirlโitโll make sure your cookies never go stale on you!
Alright, letโs dive into the hilariously profound world of Laravel testing! In this section, weโre going to talk about assertSee. Itโs like being a psychic detective on a web page, but with code! ๐ต๏ธโโ๏ธ๐ฎ
So, if youโve got a gut feeling (or better yet, cold hard evidence) that some specific text is lurking around your web page, assertSee is here to help. Just whip up a spell (erโฆ function), and cast it on the text in question:
$browser->assertSee($text);
This magical incantation will ensure that the text you specified is, without a shadow of a doubt, present on the page. If it isnโt, well then, your suspicions are confirmed โ thereโs definitely something fishy going on over there! ๐ ๐ต๏ธโโ๏ธ
And just in case youโre expecting an unexpected guest (orโฆ text), Laravelโs also got a nifty little counterpart for when you want to make sure the text is not present:
$browser->assertDontSee($text);
Now, if you thought that was all there was to it, prepare to be amazed (or amused)! This function doesnโt just take plain old text, but also CSS selectors and XPath expressions. Itโs like the Laravel version of Sherlock Holmes with a side of Dr. Strange! ๐ต๏ธโโ๏ธ๐งโโ๏ธ
So, go ahead and use your powers for good (and for testing web pages), and remember: with great assertSee comes great responsibility! ๐ช๐๐ฉ
Ahoy there, coding seafarers! Letโs set sail for a fun voyage into Laravelโs assertDontSee function, shall we?
Fasten your life jackets and grab your monocles (itโs a pirate thing), because this function is about to ensure that the text you specify ainโt dancing a jig on your web page!
$browser->assertDontSee($text);
Translated into buccaneer-ese: โAvast, matey! Make sure this here $text isnโt hogging the plank and causing trouble!โ
Now remember, if you see the text in question parroting around or walking the plank, assertDontSee will raise an alarm, so you can set your compass straight without worrying about mutinous monkeys!
Happy coding, mateys! May your code be swift and your test results fair wind!
Alrighty, letโs dive into a Laravel-icious exploration of assertSeeIn. Imagine youโre hosting a secret garden party, and you want to ensure your guests are mingling in the right spot. Thatโs where our digital butler, the $browser, comes in!
$browser->assertSeeIn($selector, $text);
In this scenario, $selector is the velvet rope-lined area you want to check (think: dance floor, punch bowl, or that mysterious tent). And $text? Well, thatโs your guest of honorโs name or the secret recipe for the homemade sangria. So if you want to make sure the right folks are grooving where they should, or that the punch isnโt accidentally labeled as the sangria, this is your go-to command!
Just like a well-rehearsed security guard checking IDs at the door, assertSeeIn will keep an eye out for the specified text within your chosen area (selector). Itโll let you know if everythingโs kosher or if itโs time to call in backup and find that missing ingredient! ๐ทโจ
Alright, letโs get this party started! In the world of Laravel, weโve got a tool thatโs perfect for those moments when you just know somethingโs missing, but canโt quite put your finger on it. Itโs called assertDontSeeIn, and itโs here to save the day (or at least your code)!
Imagine youโre hosting a grand feast, but youโve mysteriously run out of guacamole. You know it should be there, but itโs nowhere to be found. Thatโs where assertDontSeeIn comes in - itโs like having your own personal Avenger for coding disasters!
Hereโs how you summon this coding superhero:
$browser->assertDontSeeIn($selector, $text);
Just replace $selector with the HTML element youโre investigating (e.g., a div, span, or even your secret stash of empanadas), and $text with what youโre certain is nowhere to be found (the missing guacamole).
With assertDontSeeIn, you can rest easy knowing that Laravel will double-check the element for you. If it doesnโt find your missing item, itโll throw a friendly exception, giving you all the info you need to track down the culprit and reclaim your guacamole (er, fix your code)!
So next time youโre puzzling over an empty plate in your HTML buffet, remember assertDontSeeIn. Itโs like having a personal butler who double-checks the kitchen before bringing you your meal. Happy coding, and may all your guacamoles forever be accounted for! ๐ฅ๐
assertSeeAnythingIn (AKA โSpot the Differenceโ)
Gather โround, coding cowpokes! If youโre looking to catch a sneaky snippet of text lurking within your HTML elements like a digital barn dance bandit, this here functionโs for you!
$browser->assertSeeAnythingIn($selector);
Just throw in your selector like youโd toss a lasso to a coyoteโand let the fun ensue! This cowboy-friendly command ensures that the Wild West of your webpage wonโt hide any wanted text from ya, keeping the peace (or errors) at bay. Yee-haw! ๐ค ๐ต๐ธ๐ด
Alrighty then, letโs dive into the world of Laravel testing with a splash of humor! Todayโs star is the assertSeeNothingIn function. Imagine youโre at a party and you donโt want to see your least favorite dance move or that one person who insists on playing air guitar. You canโt just disappear, right? Well, in Laravel, your code doesnโt have to!
So, when you want to ensure that thereโs absolutely no text matching a certain selector (think of it as a dance move in the HTML disco), you can simply call:
$browser->assertSeeNothingIn($selector);
Just replace $selector with the HTML element or class you wish to scrutinize, and voila! Your code will do the dancing (or rather, checking) for you. Happy testing! ๐๐๐ผ๐บ๐ผ
Alrighty then! Letโs dive into the magical world of Laravelโs assertion wizardry with the enchanting assertCount spell. This ainโt your grandmaโs basic count function, oh no! Itโs a badge of honor for Laravel developers who know their stuff.
Hereโs how you cast this spell:
$browser->assertCount($selector, $count);
So whatโs assertCount all about? Well, imagine youโve summoned a horde of HTML elements with a specific selector (think โfind-by-CSS class or IDโ), and you want to make sure that the correct number of those little digital critters have appeared on your webpage. Thatโs where assertCount comes in handy!
Just tell it which selector youโre interested in, and how many times you expect to see them. If they donโt match up, watch outโyour test will fail faster than a rookie developer trying to write clean code! ๐คช๐ฃ
Ahoy there, code wranglers! ๐ค Letโs dive into the mystical world of Laravel testing, shall we? Today, weโre going to talk about a function thatโll make your browser dance like a marionette on strings: assertScript!
Now, imagine youโve got a finicky JavaScript expression that just wonโt behave. Fret not, because this function is here to tame the wild beast and ensure it dances in line with your expectations! ๐ฏ
$browser->assertScript('window.isLoaded')
->assertScript('document.readyState', 'complete');
In plain English, this means:
- Check if
window.isLoadedevaluates to true. If not, prepare for a good chuckle as your browser gives you the โuh-uh, not yetโ face! ๐ - Make sure
document.readyStateis set to โcompleteโ. If itโs still in the process of cooking up like a soufflรฉ (read: loading), youโll get a friendly reminder to wait for your document to stop dancing and take its seat! ๐บ๏ธ
And there you have it, folks! With assertScript, you can make your browser obey like a well-trained seagull! ๐ฆ Keep on testing, and happy coding! ๐๐ป๐ป
Alright, buckle up, coding cowboys! Hereโs a chuckle-inducing dive into Laravelโs assertSourceHas. Imagine youโre on an episode of โCSI: WebPageโ, and you need to ensure that some sneaky script or CSS magic is actually present on your webpage. Well, pull out those digital magnifying glasses because assertSourceHas is here to help!
$browser->assertSourceHas($code);
This magical line of code is the digital equivalent of shouting โFreeze! Put that HTML/CSS/JavaScript up against the screen!โ Itโll make sure that whatever $code youโre looking for isnโt pulling a Houdini act and disappearing from your page. Just remember, when in doubt, let this assertion be your faithful sidekick in the quest for code integrity!
Oh, and if you ever find yourself in need of proving that something is absolutely not on the page, you can hop over to its cousin assertSourceMissing. Itโs like having a built-in lie detector that alerts you when someone tries to pull a fast one with your code! ๐ต๏ธโโ๏ธ
Keep coding and chuckling, web devs! ๐๐คช
Oh, youโre in for a treat! Letโs dive into the world of Laravel, where weโre going to make sure your source code doesnโt crash the dancefloor. You see, just like DJ Khaled doesnโt want unsolicited remixes ruining his beats, you donโt want unwanted code messing up your page.
So hereโs how you can be the bouncer of your website:
$browser->assertSourceMissing($code);
In this case, $code is the sneaky piece of source you donโt want to see on your site. Imagine it as that one guest who just wonโt leave even though theyโve overstayed their welcome โ weโre kicking them out! This function ensures that your page is as pristine as a Taylor Swift album cover, free from unwanted guests.
Now, you might be wondering: โWhat if I change my mind and want that code back on the page?โ Well, in the spirit of good humor (and because weโre nice people), just invite it back with $browser->assertSee() โ weโll show you how to do that in another doc, donโt worry! But for now, letโs keep the dancefloor clean and enjoy the music! ๐ถ๐
The Link Whisperer! ๐งโโ๏ธ
Call upon our mystical browser, the one who can see through HTML soup and webpage fluff, to verify if a certain magical link is present on the page:
$browser->summonLinkWhisperer($linkText); ๐ฉโจ
And, for when you want your magical link to disappear (because itโs not supposed to be there), use this dark arts counterpart:
$browser->banishLinkWhisperer($linkText); ๐งน๐ท๏ธ
Just remember, even the Link Whisperer canโt find a link if it doesnโt exist or if itโs hidden behind an enchantment like display: none. So donโt forget to cast your own spells on the CSS and HTML! ๐งโโ๏ธ๐ฎ๐
Ahoy there, coding pirates! Letโs set sail on an exciting journey with Laravelโs mighty assertDontSeeLink function, shall we? This handy dandy tool is perfect for ensuring your web pages are as shipshape as a scurvy dogโs peg-leg.
In plain English (or swabbie talk), this function checks if the specified link isnโt lurking around your page like a sea monster in murky waters. Hereโs how you can use it:
$browser->assertDontSeeLink($linkText);
Imagine this scenario: Youโve built a treasure map website, but youโre worried about X Marks the Spot leading to Davy Jonesโ locker instead of real gold. No worries, mate! Just point $linkText at your suspect link and our trusty assertDontSeeLink will make sure it doesnโt lead to danger. If it does, wellโฆ you might want to take a detour for that one! โ ๏ธ๐ดโโ ๏ธ
So there you have it, me hearties! With Laravelโs assertDontSeeLink, keeping your pirate treasure map websites safe from perilous links has never been easier. Arr matey, happy coding! ๐๐ป
Ahoy there! Setting sail on a journey through the vast seas of Laravel land? Buckle up, matey! Today weโre diving into the mysterious depths of the assertInputValue function. Yarr!
Ready your treasure map and follow me closely, as we navigate the shores of testing in this here Laravel lore.
So youโve got a form with a field that needs to be checked for a specific value? Well, let us introduce ye to assertInputValue. Itโs like a pirate parrot that can squawk out whether your input matches the desired treasure!
$browser->assertInputValue($field, $value);
Just replace โ$fieldโ with the name or id of your input field and โ$valueโ with the treasure youโre hunting for. Itโs as easy as counting your gold doubloons and swabbing the deck!
Now if you find yourself in a predicament where you need to ensure that your input is NOT equal to something, fret not, me hearty! The assertInputValueIsNot function will set sail to those waters and bring back the truth. More on that later, but for now, hoist the Jolly Roger and letโs conquer these tests together!
Arrrr, we hope this shanty helped you find your way through the Laravel sea of functions! Happy testing!
Alrighty, letโs get this party started! In the fascinating world of Laravel testing, we stumble upon a gem called assertInputValueIsNot. This little guy is here to ensure that your input field is as single as a pringle (nope, not in love) with a particular value.
So, how does it work? Simple! Just imagine youโre playing a game of โWhatโs in the box?โ but instead of surprises, weโre looking for the opposite โ what ainโt in the box!
Hereโs the magic incantation:
$browser->assertInputValueIsNot($field, $value);
In this code, $field is your input field (think of it as a mystery box), and $value is what youโre hoping to not find inside that box. So if you donโt want your field to be filled with โkitten photosโ or โchili recipes,โ just let this function know!
Now, keep in mind that while assertInputValueIsNot may bring a smile to your face, itโs still a powerful tool for keeping your tests squeaky clean. Happy testing, and remember: if you assert something, be prepared to defend it! ๐ฅ ๐
Alright, letโs get this party started! In the world of Laravel testing, we sometimes need to ensure that certain checkboxes have been properly ticked - no pun intended. And for that, weโve got a superhero in our toolkit: assertChecked!
Hereโs how you summon this mighty warrior:
$browser->assertChecked($field);
Now, imagine yourself in a room filled with checkboxes. Youโre the checkbox detective and your mission is to find that one checkbox thatโs been sneakily checked amidst all the others. Thatโs what assertChecked does for you, minus the trench coat and magnifying glass (but feel free to add them if it makes you feel fancy).
Remember, this function checks if the specified field is, in fact, checked. If itโs not, wellโฆ we might need to have a word with that checkbox!
Now go forth and test your checkboxes with confidence, knowing that assertChecked has your back (and your boxes). Happy testing! ๐๐๐๐ต๏ธโโ๏ธ
Oh, the joys of programming! Ever felt like your code needed a good old-fashioned smack in the face to make sure itโs behaving itself? Well, meet assertNotChecked, your digital doorman at the gate of checkbox chaos.
Just picture this: youโve got a checkbox thatโs gone rogue and decided to play hide and seek with its checked status. Instead of tearing out your hair or chasing after it with a net, simply call $browser->assertNotChecked($field)โa one-liner thatโll slap some sense into that misbehaving checkbox!
Think of it as a digital version of those stern glares you give to your pet when theyโre misbehaving. In this case, the pet is a checkbox and the glare is a PHP function that checks if the box isnโt checked (clever, huh?).
So next time youโve got a stubborn checkbox on your hands, remember to keep it in line with assertNotCheckedโbecause who needs a behavioral therapist when youโve got Laravel? ๐
Oh, the drama of the unresolved! The eternal question mark lingering over a humble checkbox in your Laravel app. But fear not, dear developer, for help is here! Enter assertIndeterminate(), the superhero that swoops in to save the day when youโre unsure about your checkboxโs state of undecidedness.
How does it work, you ask? Well, just point this function towards your pesky checkbox:
$browser->assertIndeterminate($field);
This code is like saying to Laravel, โHey there, app! This field right here? Itโs a checkbox and itโs acting all โI canโt decideโ, so could you kindly confirm that for us?โ And Laravel, being the good sport that it is, will do just that.
Now go forth and tame your unruly checkboxes with assertIndeterminate(), and may all your boxes forever be either checked or unchecked, but never in an ambiguous state! ๐
Ahoy there, fearless Laravel coder! Today weโre diving into the shimmering depths of a feature that will make your web applications sparkle with validation brilliance: assertRadioSelected().
This is the function you want to grab when youโve got a hankering for verifying that a specific radio button in your HTML form has been, in the immortal words of Captain Picard, โmade ready.โ
To use it, simply summon its powers with this incantation:
$browser->assertRadioSelected($field, $value);
Now, allow me to explain this little magic trick. Imagine youโve got a form for your users to choose their favorite space-faring speciesโhumans, Vulcans, or Klingons (and yes, we know there are no aliens on Earth, but bear with us). You want to make sure that when they hit submit, theyโve actually selected something.
assertRadioSelected() swoops in, checks if the chosen species matches the $value, and makes sure itโs the one selected among all radio buttons with the same name (thatโs what she saidโฆ about the radio fields, not space-faring species). If everything checks out, your app will continue its journey through the stars. But if it finds that some intergalactic mix-up has occurred, assertRadioSelected() will throw an exception, giving you a chance to correct the error and save your users from the embarrassment of choosing Klingons when they meant Vulcans (or vice versa).
So there you have it! With assertRadioSelected(), you can boldly go where no web application has gone beforeโvalidating user input with ease, humor, and a touch of the final frontier. May your forms always be selected, and your users forever satisfied!
Radioโs Got the Blues (But We Ainโt Selected)!
Ready to play radio detective? Hereโs your badge: $browser->assertRadioNotSelected($field, $value);
Thatโs right! Youโre now a Laravel gumshoe on the case of the unselected radio field. Just drop this snippet into your code and let it handle the heavy lifting while you kick back with a cup of debuggerโs coffee.
But remember, partner, this isnโt about catching crooks; itโs all about verifying that a particular radio button ainโt been tickled by our user. If the radio field in question ($field) and its value ($value) are not in cahoots, then this function will raise an alarm, ensuring your application stays on the straight and narrow!
Now, who needs Sherlock Holmes when youโve got Laravelโs assertRadioNotSelected? Investigate, verify, and ensure your appโs radio fields keep their cool โ all without the need for a deerstalker hat. Happy coding! ๐ต๏ธโโ๏ธ ๐
Ahoy there, code pirates! Letโs set sail through Laravelโs enchanted seas and learn about the mysterious assertSelected function. This dashing function is akin to a treasure map that guides you to the gold (or selected value) in a dropdown shipwreck.
To use this swashbuckling tool, steer your browser with:
$browser->assertSelected($field, $value);
Imagine this scenario: Youโve stumbled upon an ancient treasure chest (represented by a dropdown), and youโre eager to discover which cursed gemstone (your chosen value) is hidden within. assertSelected will help you plunder the correct stone, ensuring that the treasure chest doesnโt contain another Captain Blackbeardโs doubloon instead!
Now, if you feel like rowing against the tide and checking for an unselected dropdown option, just cast anchor and navigate to the โassert-not-selectedโ section. Yarr!
Ahoy there, coding sailors! Dive into the depths of Laravel testing with us as we explore the enigmatic assertNotSelected function.
This swashbuckling command is your faithful sidekick when youโre certain that a particular dropdown shouldnโt be harboring a specific value. Hereโs how ye might use it in yer battles against untidy user interfaces:
$browser->assertNotSelected($field, $value);
Now, I know what youโre thinking: โWhat if I want to check that all the options are selected or have options at all?โ Well buckle up, matey! Laravelโs got a function for that too, and weโll sail through it together in our next adventure. But for now, letโs celebrate this fine victory with a hearty โYarrrr!โ for assertNotSelected!
Ahoy there, Laravel coders! Letโs embark on a jovial journey through the enchanting realm of assertions with our trusty sidekick assertSelectHasOptions.
Imagine youโre at a fancy dinner party, and you need to ensure your favorite ice-cream flavors are available for dessert. Well, in our digital dinner partyโthe HTML formโassertSelectHasOptions is the perfect butler to help you out!
$browser->assertSelectHasOptions($field, $values);
In this elegant dance of code, $field represents your beloved ice-cream flavor section, and $values is a suitcase full of scrumptious flavors you want to verify. So, when you call upon assertSelectHasOptions, it checks whether all those flavors are indeed present in the ice-cream selection!
Now, if by any unfortunate circumstance your favorite flavor isnโt there, fear not! assertSelectMissingOptions is the other cheeky helper that will let you know who snuck a taste before you arrived. Just remember to check out its documentation for more information on how to use it.
So, have fun keeping your HTML forms in check with this delightful assertion duo. Happy coding! ๐๐ฆ๐
Alright, letโs get this party started! In the vast world of Laravel, where code and comedy often go hand in hand (like a well-balanced sandwich), we find ourselves at the crossroads of assertion and selection - a place called assertSelectMissingOptions.
Now, what on earth is that you ask? Well, imagine this: Youโre hosting a super swanky dance floor party, and youโve got a guest list for the DJ to play only specific tracks. But the DJ, in his infinite wisdom, decides to spin some tunes outside of your selection. Youโd be furious, right? So, youโd want a way to ensure he only plays what you asked for - this is where assertSelectMissingOptions comes into play!
In Laravelese (our new made-up language), this magical function goes like this:
$browser->assertSelectMissingOptions($field, $values);
Here, $field represents the dance floor, and $values are your carefully curated playlist. If, by some unfortunate turn of events, the DJ decides to spin a track thatโs not on your list, this function will raise an alarm - ensuring your party remains as you intended! ๐ฅณ๐๐๐บ๏ธ
The One That Yells When You Forget an Option! ๐ฃ
Ever found yourself in a pickle, wondering if that dashing value of yours is actually available for selection on the swanky field youโve got your eye on? Well, fear not, my dear friend! Introducing: $browser->assertSelectHasOption($field, $value) - the party-crasher of pickles everywhere. ๐
This little gem ensures that your sparkling value is indeed a contender in the fieldโs grand selection process. Just drop it into your code like a well-timed punchline at a comedy club, and watch as it saves you from countless headaches caused by missing options. ๐คฏ
But what if the option is nowhere to be found? Oh, donโt worry - this comedian doesnโt just tell jokes; it also knows how to take the spotlight when somethingโs amiss. Itโll help you identify those pesky missing options with its assertSelectMissingOption function. Now thatโs what I call a true all-rounder! ๐
The โNo-Selection Nonsenseโ (assertSelectMissingOption)
Are you tired of that one rebellious option in your HTML forms that just wonโt play ball? Well, donโt worry, weโve got your back with the Laravel โNo-Selection Nonsenseโ! ๐๐คนโโ๏ธ
Hereโs how to use it:
$browser->assertSelectMissingOption($field, $value);
So if you ever find yourself scratching your head wondering where on earth that mischievous option went, give our No-Selection Nonsense a spin! ๐ต๏ธโโ๏ธ๐ Itโll help keep your forms tidy and your sanity intact. Just remember to replace $field with the name or ID of your field, and $value with the value youโre looking for. Happy no-selecting! ๐๐ช๐ป
Ahoy there! Sailors of the Laravel seas, prepare to hoist the flag of assertion! ๐ดโโ ๏ธ๐
Youโve stumbled upon the mighty assertValue function, a swashbuckler among the PHP array functions. This pirate is here to ensure that the element, identified by the glorious selector youโve provided (yes, ye olde CSS selectors work here), contains the treasure chest of a value youโre after.
Hereโs the catchy command to call upon this assertive matey:
$browser->assertValue($selector, $value);
Remember, ye scurvy dogs, itโs not just about verifying any olโ value! This function will only sing a joyous shanty if the sought-after value matches the current one displayed on the web page. So if youโre looking to make sure that โCaptain Jackโ isnโt pretending to be โWilliam Turnerโ, this is the php pirate ye want aboard! ๐ดโโ ๏ธ
Now, letโs set sail for adventure with assertValue and keep our tests shipshape! Happy coding, me hearties! ๐๐ณ
Ahoy there, code sailors! Letโs set sail on a fun journey through Laravel land, shall we? Today, weโre diving into the mystical waters of assertValueIsNot, a magical function that ensures your web pages are as unpredictable as a jesterโs jokes!
Picture this: youโve written some enchanting code to select an element on your webpage using a selector, much like a pirate deciphering treasure maps. But what if you want to make sure that this chosen element doesnโt hold the value you least expect? Enter assertValueIsNot, your new best friend!
Hereโs how to summon this function:
$browser->assertValueIsNot($selector, $value);
Just replace $selector with the key to unlocking that element, and $value with the surprise you donโt want to find there. Imagine if your browser could tell jokes as well โ it would say something like: โArr matey! I be expecting gold, not a llama in yer booty!โ And if the element doesnโt contain the unexpected value, itโd raise its glass and cheer, โAye, that be a good one!โ
So, donโt let those sneaky web pages pull a fast one on you. With assertValueIsNot, you can make sure your code is as unpredictable as a jesterโs riddles, but in the best possible way!
Ahoy there, code pirates! Steer your vessel towards this tantalizing Laravel method that goes by the name of assertAttribute. This seaworthy function is designed to ensure that Jack Sparrowโs compass points true north (or whatever you want it to point to, but in our case, elements on a web page).
To deploy assertAttribute, hoist the sails of your PHP ship and unsheath your code saber:
$browser->assertAttribute($selector, $attribute, $value);
Translation for landlubbers:
$browser- Your trusty sea vessel (or web browser, to be precise).$selector- The treasure map coordinates that pinpoint the element youโre after.$attribute- The pirateโs chest key that unlocks the value youโre seeking.$value- The buried gold youโre hunting for, to make sure it matches whatโs in the chest.
Now, set sail and navigate through the seas of web pages with this swashbuckling function! Keep a firm grip on your code saber, as this method will ensure that the element matching your treasure map coordinates has the expected value within the attribute you specify. Arrr matey!
Ahoy there, code pirates! Steer your keyboard towards Laravelโs swashbuckling assertion feature - the assertAttributeMissing!
Ever found yourself in a pickle trying to verify that an element on your web page has no trace of a specific attribute? Well, matey, youโve struck gold with this one! Hereโs how ye use it:
$browser->assertAttributeMissing($selector, $attribute);
Just replace $selector with the CSS selector for your target element and $attribute withโฆ well, the attribute you wish to ensure is absent. And there you have it! This command will check if the specified attribute ainโt hanging around your element like a parrot on a shoulder.
Now, if only we could use this magic to verify that no oneโs left a talking cat in our codebaseโฆ arrrrgh! But letโs not get too carried away โ back to business! Enjoy sailing these waters of Laravel assertions, and may your tests be swashbucklingly successful!
Ahoy there, code wranglers! Sail with me as we delve into the mystifying waters of Laravelโs assertAttributeContainsโthe seafaring navigator you never knew you needed but will quickly realize you canโt live without!
Fasten your lifejackets and prepare to set sail:
$browser->assertAttributeContains($selector, $attribute, $value);
In plain English, this command is shouting at the browser (in a polite manner, of course) that it better find an element matching the provided $selector, and check if that elementโs specified $attribute contains the $value like a well-stuffed pirateโs parrot!
Now, letโs say you need to ensure that your treasure map (HTML DOM) includes a specific island (element), with the right compass direction (attribute), and it points towards Captain Goldbeardโs hut (value). In such a case, this command becomes your trusty compass:
$browser->assertAttributeContains('#treasure-island', 'direction', 'Northwest');
Happy coding, swashbucklers! May you find all the buried treasure and avoid scurvy rats (errors) along your Laravel journey. ๐ดโโ ๏ธ๐ด๐ข
Ahoy there, code wrangler! Fancy a jolly journey into the heart of Laravelโs assertive arsenal? Buckle up as we delve into the enchanting world of assertAttributeDoesntContain!
Picture this: Youโre on a quest to ensure your web appโs user interface is as pristine and error-free as an Elizabethan sonnet. But how do you guarantee that your HTML doesnโt contain a particular attribute value like the infamous โMisspelled Sans-serifโ? Fear not, intrepid explorer! The assertAttributeDoesntContain is here to save the day!
$browser->assertAttributeDoesntContain($selector, $attribute, $value);
Just remember that itโs more like a snooty butler checking for any unwelcome guests in your fine web manor. You provide the selector (the snazzy duds heโs searching for), attribute (the peculiar detail to examine), and value (the nosy neighbor causing all the ruckus).
So, keep your code squeaky clean, and may your interfaces be as elegant and sophisticated as a 17th-century ballroom dance! And remember: a well-dressed web page is a happy user! Happy coding, adventurer! ๐๐บ๐ผ๐๐ผ
Unleash the Aria-tic Assertion! ๐ต๐บ๏ธ
Welcome, web warriors! Itโs time to flex your Laravel muscles and dive into the world of accessible assertions with our dance-tastic assertAriaAttribute function.
Ready for the beat? Just follow these simple steps:
- Choose your selector, like a seasoned diva on stage:
$selector = 'button'; ๐ค ๐๏ธ
- Whisper sweet nothings into the aria attributeโs ear (you know, the one with the provided name):
$attribute = 'label'; ๐ต ๐บ๏ธ
- And finally, demand that it dances to your desired value:
$value = 'Add'; ๐๏ธ ๐
Combine the three and watch the magic happen with this rhythmic routine:
$browser->assertAriaAttribute($selector, $attribute, $value);
Now, if your markup is a snazzy <button aria-label="Add"></button>, youโll have no problem checking that โAddโ is the one dancing with the aria-label attribute:
$browser->assertAriaAttribute('button', 'label', 'Add') ๐๏ธ๐๐ต
Donโt be shy, show off your A11y assertion skills! ๐ช๐๏ธ๐
Oh, the dance of digital elements! You know, itโs a bit like trying to find Waldo in a crowd of stripes and spectacles, but with data attributes instead. Letโs introduce you to your new best friend, assertDataAttribute. This function is akin to shouting โHey, you over there with the specific attribute value!โ across the web page.
Hereโs the rundown:
$browser->assertDataAttribute($selector, $attribute, $value);
Imagine having a dinner party, and you need to make sure each guest is sitting at the right table. Thatโs essentially what assertDataAttribute does for your web elements!
Take our friend <tr id="row-1" data-content="attendees">, for instance. If you want to ensure that row oneโs content indeed involves attendees, you can assert like so:
$browser->assertDataAttribute('#row-1', 'content', 'attendees');
And just like that, your code has the superpower to check data attributes and make sure everything is in order. Now, go forth and assert with confidence! ๐๐ค๐ป๐พ๐
Ahoy there, code pirates! Steer clear of those treacherous invisible waters with our trusty Laravel Lifeboat, the assertVisible() function! โ ๏ธ๐ฃโโ๏ธ
Just point it at the HTML booty you seek, and itโll ensure that pirate ship of yours doesnโt sail off course. Here be the syntax:
$browser->assertVisible($selector);
Now donโt go walkinโ the plank without knowing this: $selector is the CSS selector for the element you want to keep an eye on. Itโs like saying โArr matey, show me that button with the class โmy-buttonโโ! ๐โจ
So hoist the Jolly Roger and set sail for clear skies, knowing your webpage elements will never go overboard without your knowledge again! ๐ด๐ ๐ดโโ ๏ธ
Ahoy there, code pirate! Sail into port with us for a lively lesson on Laravelโs assertPresent. Itโs like swabbing the deck, but instead of looking for sea monsters, weโre keeping an eye out for HTML elements!
Ready to set sail? Steer your ship towards that CSS selector youโve got stowed away. Once youโve found it, you can use $browser->assertPresent($selector) to make sure your vessel is anchored near a valid element. This commandโll hoist the flag and declare victory if it finds your element in the HTML source.
But wait! You might be thinking, โWhat if I donโt want to deal with those pesky elements?โ Well, buckle up, matey! Weโve got another command for that: assertNotPresent. This one will let you know if an unwanted element is lurking about. Sailing blind ainโt no fun, and neither is dealing with undesirable HTML elements.
So grab your telescope and keep a sharp eye out, because itโs all hands on deck to conquer the seas of Laravel testing!
Ahoy there, code wranglers! Letโs sail into Laravelโs enchanting world of assertions, shall we? Today, weโre going to talk about a magical spell called assertNotPresent. This isnโt your run-of-the-mill โhey, is that present?โ spell. No sirree! Itโs more like a โhey, is that not here?โ incantation.
So, how does it work? Simple as pie (or as simple as Laravel code can be, anyway). You see, you give olโ assertNotPresent a selector โ thatโs just a fancy name for a treasure map to your HTML element of interest. Then, our trusty spellcaster checks if said element is nowhere to be found on the page.
Hereโs a bit of code that demonstrates its mystical prowess:
$browser->assertNotPresent($selector);
Now, if you ever find yourself wondering whether your favorite dancing hamster has disappeared from the page, assertNotPresent is the go-to charm. Itโs like a lighthouse for lost elements. Happy coding, pirates! ๐ฆ๐โ๏ธ
Ahoy there, Laravel enthusiasts! Letโs dive into a jolly good adventure with assertMissing โ the swashbuckling function that ensures your website is as mysterious as Captain Hookโs missing hand!
Say youโve got a treasure map (selector) and youโre on the lookout for X Marks the Spot (an element). But, alas, the spot be empty! How do we prove it, ye say? Simple, with this magical incantation:
$browser->assertMissing($selector);
Just like Sherlock Holmes deducing a crime from a single strand of hair, assertMissing uses its keen eye to check if the element matching your selector is nowhere to be found on the page. Itโs as easy as pie (or treacle tart, if youโre in Yorkshire)!
So hoist the Jolly Roger and set sail for a thrilling voyage with Laravelโs assertMissing โ ensuring your web treasure hunt never leaves you high and dry! Yarr-ghastly fun! ๐ค๐ดโโ ๏ธ
Alright, letโs dive into the world of Laravel testing! When you need to check if a certain input with a swanky name is indeed present on your form, fear not - our friend assertInputPresent() has got you covered!
Just like calling out for that missing party guest, you can ensure your form isnโt playing hide-and-seek with you by using this snazzy function:
$browser->assertInputPresent($name);
Now go forth and test with confidence, knowing that youโve got a reliable posse in Laravel! ๐ค
Itโs a Laravel Party, and the Input Refuses to Dance!
Oh, youโve got an input with a name thatโs just not showing up at your Laravel soiree? No worries, weโve got you covered! Just like a good bouncer making sure no uninvited guests crash the party, our function will do the same for your inputs.
$browser->assertInputMissing($name); // Because who invited that wallflower to the dance floor?
Now, go on and enjoy your Laravel event knowing unwanted inputs wonโt gatecrash! ๐ฅณ๐๐บ๐พโจ
Ahoy there, coding buccaneers! Letโs set sail into the sea of Laravel funness with a command as dashing as Captain Stubbington himself - $browser->assertDialogOpened($message).
Imagine youโre at a swashbuckling soiree and suddenly, a ghostly pirate pops up with a riddle. You wouldnโt just stand there like a landlubber, would ya? Youโd demand that ghost pirate to reveal his hidden treasure! Thatโs what this function does, but instead of ghost pirates, it verifies if a JavaScript dialog with the given message has been opened.
Just remember to replace โmessageโ with the riddle your dialog is spouting. Now, donโt be a sluggish sailor, get testing those dialogues, matey! Arrrr, good luck, and happy coding!
Ahoy there, Laravel coders! Letโs have a jolly time diving into the depths of our trusty assertEnabled function.
Ever found yourself in a pickle trying to ensure that your field is as active as a three-toed sloth on caffeine? Fear not, me hearty! The assertEnabled($field) function has got your back!
$browser->assertEnabled($field);
Just like making sure the lights are on before jumping into a pool, you now can rest assured that your fields are all switched on and ready for some action. If not, watch out for the splash of disappointment! ๐ฆ๐๐ฑ
But hey, if by any twist of fate (or user error), itโs disabled, feel free to give assertDisabled a spin instead! ๐
Now that weโve had our giggle, letโs carry on with some swashbuckling coding and conquer the digital seas together! ๐ดโโ ๏ธ๐
Unleash your inner detective, my friend! Itโs time to solve the case of the grumpy input field. Hereโs how you can do it with our very own Laravelโs Assertive Detective (AD) tool:
$browser->callInSherlockHolmesVoice("Elementary, my dear user! Let's ensure that field #{$field} is not accepting any more secrets."), $browser->assertDisabled($field);
Remember, this is like telling your pet cat to stay off the keyboard - you donโt want it clicking around when youโre trying to solve a mystery! Just replace $field with the ID of your input field thatโs acting up.
And if you ever need help proving that a button is enabled instead (because why not add some twist to this detective story?), hereโs how:
$browser->callInColumboVoice("Just one more thing, ma'am. Let me verify that button #{$button} is ready for action."), $browser->assertEnabled($button);
Now, get out there and solve those form mysteries like a boss!
Ahoy there, intrepid developer! Buckle up as we delve into the whimsical world of Laravel testing with our trusty friend assertButtonEnabled().
Remember that time when you accidentally clicked on a disabled button during your lunch break, and the universe seemed to shatter around you? Well, fear not any more! This here function will help you ensure that the button youโve chosen wonโt leave you hanging like an awkward dance move. Just point it towards your button of choice:
$browser->assertButtonEnabled($button);
Itโs like having a guardian angel watching over your buttons, ensuring theyโre always ready to dance when you call upon them! ๐บ๏ธ๐
Now, if you find yourself in a pickle where the button should be disabled instead, fear not! We have another function just for that - assertButtonDisabled(). But thatโs a tale for another time. For now, let your buttons dance with joy knowing they can always count on our friendly assertion functions to keep them in line! ๐๏ธ๐บ๏ธ๐
Ahoy there, coding pirate! Ready to hoist the sail of testing in Laravel land? Letโs cast anchor at assertButtonDisabled, a swashbuckling function that ensures your buttons are as obedient as a parrot on your shoulder.
$browser->assertButtonDisabled($button);
In plain English, this be telling olโ browser to check if the button ye provided is in a locked state. No need to worry about those unruly users trying to click a button that ainโt ready yet! Letโs keep โem at bay and maintain order on the high seas of the web.
Arrr, youโre now one step closer to navigating these choppy waters with ease and confidence. Keep the code piracy going by exploring more functions in Laravelโs vast treasure chest! Yo ho, yarr mates! ๐ดโโ ๏ธ๐
Ahoy there, code-sailing companions! If youโve ever found yourself in a pickle trying to ensure that your chosen field is basking in the warm glow of focus, then fear not! Laravelโs got your back with the mighty assertFocused() function.
$browser->assertFocused($field);
Now, if youโre wondering what this cryptic line does, let me break it down for ya like a pirate breaking open a treasure chest. This function is here to confirm that the specified field is the one that has the spotlight shining on it. Itโs perfect for when you want to make sure your formโs attention-seeking kid isnโt getting ignored by the browser, or if you just want to check if your cat is really typing in that textbox instead of napping.
So hoist the sails, set a course for code adventure, and let assertFocused() be your faithful compass on the sea of web development! Arr matey, happy coding! โ ๏ธ๐บ๐
Alright, letโs dive into the world of Laravel testing, shall we? Where tests are as delicious as a freshly baked croissant (or maybe not quite that tasty, but still important!)
First up, we have the dashingly named assertNotFocused function. This suave gentleman is here to make sure your fields arenโt stealing the spotlight like those over-eager reality TV contestants.
To use it, simply whip out a snazzy line of code that looks something like this:
$browser->assertNotFocused($field);
In other words, youโre telling Laravel to double-check if the specified field isnโt hogging the focus like a sneaky little diva at a Hollywood party. If it is, well, your tests will let you know with a stern warning thatโs just as entertaining as a tabloid headline!
So go ahead, test away, and remember: in the world of Laravel, thereโs no such thing as too many assertions (unless, of course, they start clogging up your code like an overstuffed burrito)!
Ah, the delightful dance of ensuring your user has donned their digital dance shoes and danced their way through the authentication process! Hereโs how you can put on your own sequined tuxedo and become a disco inspector:
$browser->putOnASequinedTuxedoAndCheckIfUserIsDancingThroughTheAuthenticationProcess();
Donโt worry, it wonโt actually make your PHP code sparkle (though we can all dream, right?). But it will assert that the user is authenticated, and who doesnโt love a good dance-off against the digital security system?
Now, if youโre looking to check if the user is just hanging around in the lobby without a ticket to the party, you might want to look into this little gem:
$browser->checkIfUserIsHangingAroundInTheLobbyWearingJustABowTie();
This will ensure that your user is not authenticated and is patiently waiting for their drink tickets to arrive. So, letโs get our party started with some good old-fashioned Laravel authentication checks!
Oh, behold the majesty of assertGuest(), your trusty sidekick in the battle against unwanted login hijinks! This humble function ensures that the user, much like Forrest Gumpโs box of chocolates, is most certainly NOT authenticated.
$browser->assertGuest(); // Yep, that's our hero right there!
So next time you find yourself knee-deep in a sea of unauthorized users, remember your trusty ally assertGuest(). Itโs like having Arnold Schwarzeneggerโs โIโll be backโ line to warn you when an unwanted guest decides to gatecrash your website party! ๐คนโโ๏ธ๐
Ah, the glorious assertAuthenticatedAs! The magical incantation every Laravel wizard should have up their virtual sleeves. If you find yourself in a situation where you need to ensure that your user is as legit as a three-toed sloth at a foot convention, this spellโs for you!
Just summon it with the following enchantment:
$browser->assertAuthenticatedAs($user);
No need to wave your wand around or mutter strange incantations. Just drop that in your code, and rest assured (pun intended) that your userโs credentials have been scrutinized with Laravelโs strict security checks.
Now, remember, if youโre working on the Vue side of things:
Donโt fret, my friend! Laravel Passport can lend a helping hand. Just make sure to have your passport well in place, and you can still cast this spell using the same incantation:
$browser->assertAuthenticatedAs($user);
Happy coding, my dear Laravel alchemists! May your users always be as authentic as a kangarooโs pocket.
Alrighty, letโs dive into the world of Laravel Dusk, where testing becomes as enjoyable as a bowl of popcorn and a marathon of cat videos! ๐ฟ๐ฑ
Ever wondered if that dapper Vue component you coded is living up to its potential? Fret not, for Dusk has got your back! Letโs say youโve crafted a suave profile component that looks like this:
<!-- HTML... -->
<profile dusk="profile-component">
<!-- Profile magic happens here -->
</profile>
<!-- Component Definition... -->
Vue.component('profile', {
// Template and data goodness
});
Our profile component is a smooth talker, displaying nothing but the name of our beloved โTaylorโ. Now, if youโre feeling curious about whether Taylorโs name is being correctly displayed in your app, fear not! You can assert like a boss:
test('vue', function () {
$this->browse(function (Browser $browser) {
$browser->visit('/')
->assertVue('user.name', 'Taylor', '@profile-component');
});
});
/**
* A hilariously simple Vue test example.
*/
public function test_vue(): void
{
$this->browse(function (Browser $browser) {
$browser->visit('/')
->assertVue('user.name', 'Taylor', '@profile-component');
});
}
And if, God forbid, Taylor decides to change his name to โLarryโ, Dusk will let you know with a stern warning thatโs as sharp as a well-aimed dad joke! ๐ฃ๐
The Great โNah, Not That!โ Vue Verification Function! ๐๐
Get ready to play detective with your favorite Vue components! Hereโs how to use the assertVueIsNot function - a superhero for those who like to keep things un-matchy-matchy. ๐ฆธโโ๏ธ๐
$browser->shoutOut("I got my detective specs on!"); // Optional, but recommended for dramatic effect!
$browser->assertVueIsNot($property, $value, $componentSelector = null);
So whatโs all this about? Youโre ensuring that a specific Vue componentโs data property definitely does NOT correspond to the value youโve given it. Because sometimes, just like in real detective work, knowing what someone isnโt doing can be just as important! ๐ต๏ธโโ๏ธ๐
In this function, $property is the data property you want to verify (be a good sleuth and choose wisely!), $value is the value that your property definitely should not match, and $componentSelector is the Vue component youโre snooping around in - though if you leave it out, our detective will sniff it out on its own! ๐ต๏ธโโ๏ธ๐ฆฎโจ
Happy detecting! And remember, sometimes the best way to find a clue is by eliminating possibilities. ๐ต๏ธโโ๏ธ๐๐
Alright, letโs get this party started! ๐
assertVueContains: The Laravel Way of Saying โI Gotcha!โ
Ever been in a situation where you need to verify that your Vue componentโs data property is an array and contains a specific value? Well, strap on your coding cowboy boots because weโve got just the function for you!
$browser->assertVueContains($property, $value, $componentSelector = null);
This magical function is like the digital version of a Sherlock Holmes: itโll help you find out whether your Vue component data property (the suspect) contains the given value (the evidence). And if you donโt provide a specific component selector? No worries, mate! Itโll search the entire wild west of your components until it finds the one that fits the description. ๐
So go ahead and use this function to catch those pesky data property escapades in your Laravel applications! Remember, with great power comes great responsibility. But hey, who said coding had to be boring? ๐
Alright, letโs dive into the whimsical world of Laravel Vue testing! Hereโs a chuckle-worthy take on the assertVueDoesntContain function. ๐ถ๐ค
assertVueDoesntContain: The Party Pooper of Vue Components ๐
Get ready to join the dance floor of Vue components, but donโt forget to bring your bouncer hat! assertVueDoesntContain is here to make sure your party doesnโt get too wild.
$browser->assertVueDoesntContain($property, $value, $componentSelector = null);
This function plays the role of a fun-killer, ensuring that a particular Vue component data property is an array and doesnโt contain the unwanted guest (the $value) youโve identified. ๐ญ๐ฉ
Just like when your crazy uncle shows up at your wedding, you want to keep him out of your important Vue data properties! ๐๐คช
Remember, a happy component is a party-free component! ๐ฅณ๐๐ฝ๐บ๐ผ
Ah, the delightful dance of Dusk Pages! You know, those magical test assistants that turn a chaotic symphony of sequential actions into a beautifully choreographed ballet. Imagine writing tests like a maestro conducting an orchestra, but with less tuxedos and more automated awesomeness.
Now, letโs say you have tests that make your codebase look like itโs auditioning for a role in a circus. With Dusk Pages, you can define clear and concise actions that can be executed on any page with just one method call. Itโs like having your own personal test assistant, who, instead of fetching coffee, automates complex tasks for you!
But wait, thereโs more! Dusk Pages also let you create handy aliases for common selectors within your application or a specific page. Think of it as having a thesaurus for your testsโinstead of repeating the same selector over and over, you can just use a catchy alias instead. Itโs like turning โbuttonโ into โclick-me-nowโ.
And how do you whip up these test helpers? Well, my dear friend, itโs as easy as pie! Just follow the instructions under โ# Generating Pagesโ and voilaโyour tests will be dancing like Fred Astaire (or at least moving in a more organized manner)!
Alright, letโs get this party started! ๐ If youโre looking to create a new page object in Laravel Dusk, itโs as easy as calling the dusk:page Artisan command. This magical incantation will sprinkle your applicationโs tests/Browser/Pages directory with freshly baked page objects.
php artisan dusk:page Login ๐ (Yes, we named it after everyone's favorite activity)
Now, whereโs the fun in that if we donโt give you a little insight into configuring these pages? ๐ Hereโs your chance to play mad scientist and fine-tune your page objects.
Welcome, dear experimenter! Here is where the real magic happens. You can customize your newly created page object with the help of PHP classes. Feel free to tweak its DNA according to your testing needs. Add some personality, make it dance, or even give it a catchy nicknameโitโs all up to you!
Just donโt forget to keep your test suite clean and organized, like a well-stocked pantry for those late-night coding sessions. ๐ฅช๐โ๏ธ
Setting Up Your Pages for Fun and Profit! ๐๐ผ
By default, our pages come equipped with a trio of superpowers: url, assert, and the enigmatic elements. Letโs dive into the first two, while saving the mysterious elements for a later, more intimate conversation. ๐ต๏ธโโ๏ธ
The Charming URL Method ๐ก
Ever wondered how Laravel knows which page to serve when you enter a URL? Itโs all thanks to this charming chap - the url method. This method defines the path that will trigger your page, much like inviting someone over for a delightful dinner party.
The Assertive Assert Method ๐ผ
Now imagine youโve invited someone to your dinner party, but when they arrive, thereโs no caviar or champagne! Thatโs where our assertive friend, the assert method, steps in. This method checks if all elements on your page are as they should be - just like checking if your guests brought a thoughtful gift. If somethingโs amiss, it will let you know so you can adjust accordingly (and maybe send them home early). ๐ฅ๐
The โurlโ Method, Your Navigation Companion!
Ahoy there, Laravel adventurer! If youโre sailing the seas of web development with us, then prepare to meet your new best friend: The url method. This nautical navigator will help steer you towards the digital shores of a pageโs URL in no time!
/**
* Set sail for the URL of the page!
*/
public function url(): string
{
return '/login'; // Grab your compass, we're heading to the login port!
}
Next stop: The Assert Method - donโt miss it! ๐
The assert Party Animal
Meet your new dance partner, the assert method! This lively little fellow is here to ensure that your browser is living its best life on the specified page. Contrary to popular belief, this party animal doesnโt need a playlist or even a disco ball - but if you want to throw in some assertions, who are we to stop you? Rest assured (pun intended), these dance moves will kick off automatically when your browser does the conga to the page:
/**
* Assert that the browser is on the hottest party town.
*/
public function assert(Browser $browser): void
{
$browser->assertPathIs($this->url());
}
Now, remember, navigating to pages is like inviting this method to your party. Itโll show up, do its thing, and then hit the dance floor, no RSVP needed! ๐๐ฝ๐บ๐ผ
Navigating through the digital landscape of your Laravel app is akin to navigating through a never-ending maze of chocolate (because who doesnโt love chocolate?). First, youโve got to define a room - letโs call it a page. Once thatโs done, you can find your way into it using the magical visit method:
use Tests\Browser\Pages\Login;
It's like teleporting to the Login Room! $browser->visit(new Login);
But what if youโre already lost in the Playlist Lounge and someone drops a mystery playlist invitation on your table? You didnโt explicitly navigate there, but you need to get your chocolate-stained gloves on some selectors and methods to continue. Fear not, for the on method is here!
use Tests\Browser\Pages\CreatePlaylist;
$browser->visit('/dashboard')
->clickLink('Create Playlist') // Ooh, a magic playlist door opened!
->on(new CreatePlaylist) // And now we're in the Create Playlist Room! $browser->on(new CreatePlaylist);
->assertSee('@create'); // Let's make sure we're in the right room: check for '@create'.
Shorthand Selectors (because who wants to type โ@โ every time)?
Just like how a magician can wave his wand and summon objects, you too can make your selectors appear with just a simple wave of the @ symbol:
->assertSee('@create'); // This is our magic spell to check if we see 'Create' in our current room.
CSS-ify Your Life with Laravelโs Selector Shortcuts! ๐ต๏ธโโ๏ธ
Tired of typing out those lengthy CSS selectors like a digital peacock strutting its plumes? Fear not, dear coder! Laravelโs got your back with the delightfully named elements method. This nifty feature, hidden within page classes, lets you create breezy aliases for any selector on your page. Letโs say you want to give a nickname to the โemailโ input field of our beloved login page:
/**
* Serve up some selector shortcuts like a mixologist crafting a mean cocktail ๐น
*
* @return array<string, string>
*/
public function elements(): array
{
return [
'@email_field' => 'input[name=email]', // You can call it whatever floats your boat!
];
}
Once youโve christened this beauty, you can sprinkle it into your code like you would a pinch of CSS magic:
$browser->type('@email_field', 'taylor@laravel.com'); // We're emailing Taylor now! ๐ง
No more fumbling around with those tangled selector strings, just a sweet dance of keys and your newfound alias! ๐
Alright, letโs get this party started! Youโve just invited Dusk to your Laravel bash, and the first thing it does is whip out a snazzy tuxedo and set up shop in your tests/Browser/Pages directory. This dapper chap goes by the name of Page, and heโs got some serious moves!
Now, this suave dude has a trick up his sleeve โ the siteElements method. Imagine it as Duskโs little black book of shortcuts for all your global elements on every page throughout your application. Itโs like having a secret decoder ring that makes navigating your app as easy as pie!
/**
* Get the global element shortcuts for the site, like a boss.
*
* @return array<string, string>
*/
public static function siteElements(): array
{
return [
'@element' => '#selector', // Whoa, now that's one hot shortcut!
];
}
In this method, you can define your global element shortcuts as key-value pairs. So if you want to call an element with the id โselectorโ, just use โ@elementโ anywhere in your tests and Dusk will do the rest for you! Itโs like having a personal assistant that knows all the hidden gems in your app. Party on, Laravel! ๐๐๐ฅณ
Rockinโ Page Methods, Man!
Hey there, code cowboys and codelettes! Let me tell you about these badass page methods in Laravel Dusk, the coolest test automation tool for your PHP apps. These babies arenโt just your average run-of-the-mill functions; theyโre more like custom superpowers for your tests!
Letโs say youโre building a music management app that would make even Beethoven dance in his grave (not literally, of course). Creating playlists is an action thatโs gonna pop up everywhere in your app. So instead of repeating the same olโ logic in each test like a broken record, why not define a createPlaylist method on your page class?
<?php
namespace Tests\Browser\Pages;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Page;
class Dashboard extends Page
{
// Other page methods...
/**
* Create a new playlist, y'all!
*/
public function createPlaylist(Browser $browser, string $name): void
{
$browser->type('name', $name)
->check('share')
->press('Create Playlist');
}
}
Once youโve got the method defined, you can use it like a trusty sidekick in any test that swings by this page. The browser instance will be automatically passed as the first argument to these custom page methods:
use Tests\Browser\Pages\Dashboard;
$browser->visit(new Dashboard)
->createPlaylist('My Playlist') // You've just created a playlist, buddy!
->assertSee('My Playlist'); // Now, let's make sure it's there!
Remember, with these page methods, youโre not just testing your app; youโre rockinโ it to the test-driven beat! ๐ธ๐ค
Alrighty, buckle up, web wranglers! Components, you ask? Think of them as the swiss army knives of your Laravel app โ those oh-so-versatile gadgets that pop up everywhere from a navigatorโs compass to a notifierโs peephole. No more coding the same navigation bar or pesky pop-up window multiple times!
Now, let me tell you about generating these bad boys. Imagine youโre in a whimsical workshop, and instead of forging swords, youโre crafting components! You can even name your creation after your favorite sandwich if that floats your boat. ๐
To use these newly minted masterpieces, you simply include them in the code as needed, just like an encore by a beloved comedian at a sold-out show! Remember, components are free-range and unfettered by the confines of specific URLs. So you can plop โem down wherever you please, from the cocktail party on the homepage to the secret speakeasy in a userโs profile.
Now, go forth and build an app thatโll make your users laugh, cry, and everything in between! ๐๐ค๐ฅณ
Unleashing the Magic of Date Pickers!
Ready to conquer time travel in your Laravel app without a DeLorean? Buckle up, because weโre about to turn back the clock on boring test writing with the power of Dusk Components! ๐ฐ๏ธ
To summon a new component, just shout out the dusk:component Artisan command like a magic incantation. Hereโs our star of the show - the DatePicker! ๐
php artisan dusk:component DatePicker
A โdate pickerโ is like the time-traveling equivalent of a trusty Swiss Army knife, sprinkled throughout your application on various pages. Writing automation logic to navigate through time can be as cumbersome as herding cats in a phone booth! But fret not, because weโve got you covered with our Dusk component that neatly encapsulates all that complexity. ๐พ๐ฑ
<?php
namespace Tests\Browser\Components;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Component as BaseComponent;
class DatePicker extends BaseComponent
{
/**
* Feel the rhythm of the cosmos with us! ๐ฅ
*/
public function selector(): string
{
return '.date-picker';
}
/**
* Let's party like it's 1999! Assert that the page is grooving to our beat. ๐๏ธ๐บ๏ธ
*/
public function assert(Browser $browser): void
{
$browser->assertVisible($this->selector());
}
/**
* A secret map of element shortcuts to navigate through the ages! ๐บ๏ธ
*
* @return array<string, string>
*/
public function elements(): array
{
return [
'@date-field' => 'input.datepicker-input',
'@year-list' => 'div > div.datepicker-years',
'@month-list' => 'div > div.datepicker-months',
'@day-list' => 'div > div.datepicker-days',
];
}
/**
* Set the coordinates for your time machine and hop aboard! ๐
*/
public function selectDate(Browser $browser, int $year, int $month, int $day): void
{
$browser->click('@date-field')
->within('@year-list', function (Browser $browser) use ($year) {
$browser->click($year); // Time-traveling tip: remember to click the year! ๐ฐ๏ธ
})
->within('@month-list', function (Browser $browser) use ($month) {
$browser->click($month); // Now let's fast forward to the right month! โฉ
})
->within('@day-list', function (Browser $browser) use ($day) {
$browser->click($day); // And finally, select the day you wish to visit! ๐
});
}
}
And there you have it! Now, you can travel through your appโs history with ease and style. Stay tuned for more time-bending adventures in Dusk Components! ๐ฐ๏ธ๐๐ซ
Unleashing the Power of Pickle-Wise Calendar Navigation!
Once youโve whipped up a Date Picker component, navigating through dates in your tests becomes as easy as pie (and almost as delicious)! And hereโs the best part: if you find yourself needing to update your time-traveling skills, all you need is a quick tweak to the component itself.
<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\Browser\Components\DatePicker; // Our trusty time machine
pest()->use(DatabaseMigrations::class);
test('basic example', function () {
$this->browse(function (Browser $browser) {
$browser->visit('/') // Set our coordinates to the test URL
->timeTravelTo(new DatePicker, function (Browser $browser) {
// Hop to February 28th, 2016 in our time machine!
$browser->selectDate(2019, 1, 30); // Oh, how quaint!
})
->assertSee('January'); // Check if we're still on the right page
});
});
<?php
namespace Tests\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\Browser\Components\DatePicker; // Our trusty time machine
use Tests\DuskTestCase;
class ExampleTest extends DuskTestCase
{
/**
* A basic component test example.
*/
public function test_basic_example(): void
{
$this->browse(function (Browser $browser) {
$browser->visit('/') // Set our coordinates to the test URL
->timeTravelTo(new DatePicker, function (Browser $browser) {
// Hop to February 28th, 2016 in our time machine!
$browser->selectDate(2019, 1, 30); // Oh, how quaint!
})
->assertSee('January'); // Check if we're still on the right page
});
}
}
With the component method at your disposal, you can grab a handle to our Date Picker component:
$picklePicker = $browser->component(new DatePickerComponent); // Call it Pickle Picker for that extra zing!
$picklePicker->timeTravelTo(2019, 1, 30); // Navigate to a date of your choice
$picklePicker->assertSee('January'); // Check if we're still on the right page
Time Traveling Together in Continuous Integration
Now that youโve got the hang of it, you can embark on your time-traveling adventures with friends too! Just set up your continuous integration environment to run these tests, and everyone can join in the fun. Happy testing, pickle enthusiasts!
๐จ Attention, developers! ๐จ
Before we dive into the world of Continuous Integration (CI), letโs set the stage. You see, most Dusk CI configurations are as picky as a diva at a dinner party - they prefer your Laravel app served on a silver platter, or in this case, the built-in PHP development server on port 8000. So, before you proceed, make sure your continuous integration environment is wearing the right tuxedo (has an APP_URL environment variable value of http://127.0.0.1:8000).
Now that weโve got that out of the way, letโs talk about running tests on Heroku CI. Itโs like the ultimate backstage pass for your Laravel app! ๐ซ๐
First things first, youโll want to add a scripts section in your composer.json. Hereโs how:
"scripts": {
"post-install-cmd": [
"npm install",
"npm run production"
],
"test": "php artisan test --ansi --env=testing --deck"
}
Next, itโs time to create a .heroku/phar-auto-discover.json. This little guy will help Heroku CI find your tests and run them:
{
"bin/phpunit": {
"autoload-file": "vendor/autoload.php",
"autoload-file-map": [
"vendor/laravel/dusk": "vendor/laravel/dusk/phpunit"
]
}
}
Finally, you can rest easy knowing that your tests will run automatically whenever you push to Heroku. Lifeโs too short for manually testing code, am I right? ๐ค๐ช
Remember, the road to CI nirvana is paved with test-driven development and a love for automation. Happy coding! ๐๐
The Chromey, Phwoar-some Heroku Adventure! ๐๐
Fancy testing those Dusk tests on a cloud thatโs hotter than a Brooklyn subway in July? Letโs set up shop on Heroku CI! Hereโs the lowdown on how to get your Laravel app and Chrome driver all cozied up together like peanut butter and jelly (or avocado toast, if youโre a millennial).
First things first, open your trusty app.json file, grab a seat next to your favorite cup of code-roasting coffee, and letโs get down to business!
{
"environments": {
"test": {
"buildpacks": [ // Don't mind if we do...
{ "url": "heroku/php" }, // ...a little PHP, darling?
{ "url": "https://github.com/heroku/heroku-buildpack-chrome-for-testing" } // ...and don't forget our Chrome driver!
],
"scripts": {
"test-setup": "cp .env.testing .env", // Set up your test environment, just like you would in real life.
"test": "nohup bash -c './vendor/laravel/dusk/bin/chromedriver-linux --port=9515 > /dev/null 2>&1 &' && nohup bash -c 'php artisan serve --no-reload > /dev/null 2>&1 &' && php artisan dusk" // Run your tests like a well-oiled machine.
}
}
}
}
And voilร ! With this little dance, youโve got your Laravel app all set up to do its test-running thing on Heroku CI. Now go forth and test with confidence, knowing that your tests are being run by a trusty cloud companion as reliable as your old pair of slippers (but probably cleaner). ๐๐
Alrighty, my little Laravel buddies! Letโs frolic through the magical land of Travis CI together. Itโs not quite Disney World, but itโs where your Dusk tests will come to life (without the tears, we hope). ๐ฆ
To get started, youโll need to whip up a yummy .travis.yml recipe. Keep in mind, Travis CI is more of a black and white, no-frills kinda place, so we gotta add some extra steps to tickle out a Chrome browser. And since weโre in a digital world, letโs not forget the ever-faithful php artisan serve to launch PHPโs built-in web server!
Hereโs your tasty Travis CI configuration:
๐จ ๐ ๐ - Colors for fun, because why not?
language: php
๐จ ๐ฅง ๐ค - PHP versions, because choices are important.
php:
- 8.2
โจ Chrome-y Addons โจ
addons:
chrome: stable
Installation Time! โฑ๏ธ
install:
- ๐ Copy .env.testing to .env, because secrets are sacred.
- ๐งโโ๏ธ Run `travis_retry composer install` to make sure everything's nice and fresh. No interaction required, just like a well-oiled machine.
- ๐ Generate a new key with `php artisan key:generate`. Security is important, especially in this cyber jungle.
- ๐ฆ Set up the ChromeDriver with `php artisan dusk:chrome-driver`. Because who doesn't love a little magic?
Before the Show Begins! ๐ง ๐ฐ๏ธ
before_script:
- ing Google Chrome in its headless form, without the GPU and with remote debugging on port 9222.
- ๐ Start up the PHP server, without any reloads because we're too cool for that.
Showtime! ๐ ๐ฅ
script:
- ๐ฆ Run your tests with `php artisan dusk`. And away they go!
Now, just like that, youโre ready to dance with the testing fairies on Travis CI. Happy coding, and may your tests always pass with flying colors (and maybe even some confetti)! ๐๐
The Quest for Seamless Testing (Courtesy of the Laravel Leprechaun)
Ahoy there, brave tester! If youโve decided to hitch a ride with GitHub Actions for your Dusk tests, congratulations! Youโre about to embark on an epic adventure that would make Odysseus envious. Just like TravisCI, our trusty steed in this quest will be the magical command php artisan serve, which shall summon PHPโs very own web server, as ancient and powerful as Merlin himself!
So, letโs brew up a potion for your GitHub Actions configuration. Hereโs your starting guide to this mystical journey:
Name: The CI Chronicles
Event: When thou dost push thy code
Jobs:
Dusk Expedition:
Platform: Ubuntu, the wise and sturdy steed
Environment variables:
APP_URL: "http://127.0.0.1:8000" - The URL to thy magical app
DB_USERNAME: root - Thy faithful database keeper
DB_PASSWORD: root - Root's secret handshake with the database realm
MAIL_MAILER: log - Let's document our journey in a book!
Steps:
1. Checkout thy codebase, like pulling a sword from the stone.
2. Prepare The Environment - Copy thy .env.example to the .env, as the elixir of thy application settings.
3. Create Database - Start the magical MySQL service and create a new database, "my-database", with all the spells and incantations required.
4. Install Composer Dependencies - Install thy potion ingredients to brew the perfect test cocktail.
5. Generate Application Key - Forge a unique key to unlock the treasure chest of secrets.
6. Upgrade Chrome Driver - Enhance thy vehicle, Chrome, with the latest version of its magical horse (the driver).
7. Start Chrome Driver - Summon the mystical chromedriver-linux from its stable and prepare it for action.
8. Run Laravel Server - Invoke the php artisan serve command to ignite thy server's fire.
9. Run Dusk Tests - Unleash thy tests upon the world, and may they bring forth wisdom!
10. Upload Screenshots - If the tests fail (boo!), gather the screenshots of thy misadventures for further analysis.
11. Upload Console Logs - Should the tests continue to disappoint, collect the logs to help thee decipher the mystical errors.
This enchanted guide shall accompany you on your journey, but remember, brave tester, success is not guaranteed and monsters lurk around every corner! May the force be with thee, and may thy tests run smoothly! ๐ปโ๏ธ๐ฒ
Ahoy there, matey! Sail aboard the good ship Laravel and letโs get our coding sea legs ready! If youโre sailing with Chipper CI to conquer those Dusk tests like a true buccaneer, hereโs a jolly swabbieโs guide to setting sail. Weโll be using PHPโs own trusty vessel โ the built-in server โ to hoist our Laravel sails and prepare for battle!
Yo Ho Ho and a YARN (Yet Another Runtime Notion) file:
services:
- name: laravel
extension: php
command: composer global require laravel/installer
working_directory: /path/to/your/laravel-project
laravel_sail:
build:
context: dockerrun.aws.amz2
dockerfile: Dockerfile
command: php artisan sail
environment:
APP_ENV: testing
DB_DATABASE: testing
DB_USERNAME: testing
DB_PASSWORD: testing
BROADCAST_DRIVER: null
volumes:
- ./:/var/www/html
Arrr, this here YARN fileโll help you set up your Laravel project with Chipper CI. Itโs a treasure map for ye pirates seeking to run tests and navigate the treacherous waters of Dusk!
- First off,
laravelservice โ thatโs our ship, see? Weโre installing the mighty Laravel Installer (a handy tool weโll use throughout our voyage). - Next, we set sail with the
laravel_sailservice, which includes a Dockerfile and sets theAPP_ENV,DB_*variables for testing purposes, disables Broadcast Driver, and maps your local project to the ship. - The final command โ
php artisan sailโ raises the anchor and sets our Laravel vessel in motion!
So there ye have it, matey! With this guide, youโll be well on your way to conquering Dusk tests with Chipper CI like a true seafaring hero! Fair winds and following seas! ๐ฌ๏ธโ๏ธ๐
Alright, buckle up, PHP cowboys and code cowgirls! Letโs ride this Laravel-a-ranginโ yaml steed named .chipperci.yml.
Yโall remember that old west gold rush? Well, itโs not quite the same here but replace โgoldโ with โcodeโ and you got yourself a modern-day digital gold rush!
First off, letโs establish our version:
version: 1
Keep it simple cowpoke. You donโt want to mix up your 8-track tapes with vinyl records now do ya?
Next up, weโre setting the environment for our wild west town (a.k.a project):
environment:
php: 8.2
node: 16
Horses need food and code needs PHP version 8.2 and Node 16 to run! If youโre still using a horse-drawn buggy for your project, it might be time to upgrade!
Now, youโre ready to set off on your Laravel adventure, armed with the knowledge of this humble .chipperci.yml document. Ride โem, cowboy!
Alrighty, buckle up, cowboy! Letโs dive into the wild west of Laravel-land and discuss how to wrangle Chrome into your build environment like a seasoned mustang.
First things first, cowpoke, you gotta make sure Dusk is part of your posse by adding it as a service:
services:
- dusk
Thatโs right, olโ Dusk is our trusty sidekick when it comes to browser testing. Heโs got the chops to automate tests in real browsers, just like you wouldnโt want to round up cattle without a good olโ rope and spur!
Now, for Chrome to join the herd, we need to provide him with his necessary grub:
- Make sure you have Chrome installed on your computer; you can grab it from Google if you donโt already have it.
- Next, give Chrome a place to call home by setting the
CHROME_EXECUTABLEenvironment variable to point to your Chrome installation directory. If youโre on a *nix system (like Linux or MacOS), you can add this line to your shell configuration file:
export CHROME_EXECUTABLE=/path/to/your/chrome/application
- Last but not least, restart your good olโ Laravel homestead (or your local development environment) so these changes take effect:
vagrant reload
And there you have it, partner! Chrome is now an integral part of your Laravel build environment, ready to help you wrangle those tests and ensure your code is as tight as a cowboyโs chaps! Happy trails!
Title: ๐ Laravelโs Commit Spectacular Extravaganza ๐
# Unleash the build extravaganza on every push!
on:
push:
branches: .*
The Show Must Go On Pipeline:
1. The Grand Entrance - Setup
cmd: |
Time to don your cape and cowl, because we're diving headfirst into the setup!
cp -v .env.example .env # Tadaa! Here's your new .env file, ready for secrets!
composer install --no-interaction --prefer-dist --optimize-autoloader # The magicians of Composer are now busy at work!
php artisan key:generate # Our trusty key just got a fresh twist!
# Now, let's create a dusk env file, ensuring APP_URL uses BUILD_HOST
cp -v .env .env.dusk.ci # We've got the perfect copy for CI!
sed -i "s@APP_URL=.*@APP_URL=http://$BUILD_HOST:8000@g" .env.dusk.ci # That's better, ain't it?
2. The Show Stopper - Asset Compilation
cmd: |
npm ci --no-audit # It's time to get our assets in top shape!
npm run build # And now, the piรจce de rรฉsistance!
3. Center Stage - Browser Tests (Brought to you by the letter D and the number 4)
cmd: |
php -S [::0]:8000 -t public 2>server.log & # We've got a server! Let the tests begin!
sleep 2 # Patience is a virtue, after all!
php artisan dusk:chrome-driver $CHROME_DRIVER # Time for Chrome to step up to the plate!
php artisan dusk --env=ci # The grand finale! Let's test those browsers!
Remember, this is just the beginning of your grand adventure. For more information on running Dusk tests on Chipper CI, including how to use databases, consult the official Chipper CI documentation!