Pages with Dynamic URL Parameters in Laravel Dusk

If you are working with Laravel Dusk and have dynamic route / url parameters. You would like to configure your pages to accept the dynamic parameter so that you won’t have to create multiple pages and the page assert() method does matches your URL with the specified URL paramter.

Here is how you can do it.

Let’s say you have a profile page in your application. That has a url structure something like below

/myapplication/user/{user-id}

user-id can accept any valid integer value.

Here is how you can configure you user page to accept any value

<?php
 
 namespace Tests\Browser\Pages\professional;
 
 use Laravel\Dusk\Browser;
 use Tests\Browser\Pages\Page as Page;
 
 class userProfile extends Page
 {
 
     protected $user_id
 
     public function __construct($user_id){
            $this->user_id = $user_id;
     }    
 
     public function url()
     {
         return '/myApplication/user/'.$this->user_id;
     }
 
     /**
      * Assert that the browser is on the page.
      *
      * @param  Browser  $browser
      * @return void
      */
     public function assert(Browser $browser)
     {
         $browser->assertPathIs($this->url());
     }
 
 
 }

We have modified our page class to include a constructor that will accept the user-id passed as the class parameter. You can also pass in the whole user model if you want more data to be accessed into the page

Test

Here is how our browser test will look like

 

/** @test */
public function it_asserts_that_we_can_accesss_user_profile(){

    $user = factory('App\User')->create();

    $this->browse(function ($browser) use($user) {
        $browser->visit(new userProfile($user->id))
                ->assertUserExists();
    });
}

Thats about it !

Leave a reply:

Your email address will not be published.

Site Footer