Generating a new Page
This is how you can generate a new pagephp artisan dusk:page Checkout
I often like to go a step further and put my pages inside a directory that denotes the section that they belong to. If a particular page belongs to admin section this is how I create a new page
php artisan dusk:page admin/usersList
Pages generated are created inside tests > Browser > Pages directory.
This is how the default page class looks like
<?php
namespace Tests\Browser\Pages;
use Laravel\Dusk\Browser;
class Checkout extends Page
{
/**
* Get the URL for the page.
*
* @return string
*/
public function url()
{
return '/';
}
/**
* Assert that the browser is on the page.
*
* @param Browser $browser
* @return void
*/
public function assert(Browser $browser)
{
$browser->assertPathIs($this->url());
}
/**
* Get the element shortcuts for the page.
*
* @return array
*/
public function elements()
{
return [
'@element' => '#selector',
];
}
}
Page Default Methods
As seen in the page class code above, by default the page consists of three classesurl , assert , elemets
The url() method
The url method should return the path of the page that you are working with, Dusk will use this path to navigate to the given page. Continuing with our example of eCommerce application. If you are working with the checkout page which has a url of/myapplication/checkout . This is how the url method should look like
public function url()
{
return '/myapplication/checkout';
}
The assert() method
The assert methods get's executed when you make you call to the Page within your main test. This method is used to make sure that you are on the correct page. You can also utilize this method to make assertions to other elements or text which should be always available on the page.public function assert(Browser $browser)
{
$browser->assertPathIs($this->url());
}
By default the assert method assert that the path of the page navigated to matches which the url that we have provided in the url() method.
Pro Tip : If your page URL is contains dynamic encrypted data that cannot be exactly matched you can change assert method to use assertPathBeginsWith instead of assertPathIs, and in url just put string with which your url begins with.
The elements() method
This method can be used to give short easy to remember names for you CSS selectors of the page. Let's consider you want to assert the heading of the page which is located at CSS selector pathdiv.docs-wrapper.container > article > h1 . We can create a short-code name for this element and then can use the short-code name multiple times with-in the page methods.
public function elements()
{
return [
'@page-heading' => 'div.docs-wrapper.container > article > h1', ]; }
You can now make use of the short name in your method
$browser->assertSeeIn('@page-heading','Browser Tests');
That'a all about Pages in Laravel Dusk and Generating new Page. Next up read about Methods in Pages and Navigating to Pages.