All you need to know about Laravel Dusk

Time and time again the discontent grew amongst&nbsp;<a href="https://www.dunebook.com/best-web-development-frameworks/" target="_blank">developers</a>&nbsp;at being unable to test applications using the out of the box tools that<a href="https://www.dunebook.com/10-best-alternatives-to-laravel-homestead/" target="_blank">&nbsp;Laravel</a>&nbsp;provided. Developers wanted to use and test the JavaScript components found their Laravel apps.

Time and time again the discontent grew amongst developers at being unable to test applications using the out of the box tools that Laravel provided. Developers wanted to use and test the JavaScript components found their Laravel apps.


The long-awaited solution came in the form of Laravel Dusk.

Introduction to Laravel Dusk

Laravel Dusk charts a whole new path for developers in application testing. Application testing has been completely rewritten with ChromeDriver now the base of everything. The ChromeDriver works as a standalone diver that controls the workings of Chrome. Laravel Dusk works by sending your commands to ChromeDriver as you write your application tests. The ChromeDriver then lights up Chrome in which your tests run. While your tests run in the browser Laravel Dusk reports back to you the results.

Lavarel Dusk makes automated of browser tests in your application possible. The developers of Laravel have put out a tool that has made app functionality testing and automation very easy.

So how can you take advantage of what Laravel Dusk offers?

How To Get Laravel Dusk

Get an up to date and a recent version of the Laravel Dusk via composer.

composer require –dev laravel/dusk

As a note though; never register Dusk in your production environment in the event that you carry out a manual registration of Laravel Dusk’s service provider. If you do so random users could get access to authentication via your application.

When you are done with the installation of the Dusk package run the dusk: installcommand to complete the process and then get ready to run some tests.

php artisan dusk:install

Upon the installation, there will be a Browser directory created within a testsdirectory that will contain a test example. What come next is setting up the APP_URL  environment variable in the .env  file. The value of this APP_URL should be the same as the one you will be using while accessing your app in a browser.

You have the option of having Dusk use its own environment file. You can do this by creating a .env.dusk.{environment}  file. An example of this in a local environment file would be .env.dusk.local. This comes in handy in case you don’t want to test your current database but instead want to have a test of a test database instead.

Running Tests

When running any of your tests, make use of the dusk Artisan command. The duskcommand will accept any argument accepted by the phpunit command.

php artisan dusk

This command executes the ExampleTest within the tests\Browser\ExampleTest.php.  This gives you the result as shown below:

...
public function testBasicExample()
{
//Visit the homepage and look for the text 'Laravel'
$this->browse(function (Browser $browser) {
$browser->visit('/')
->assertSee(‘Laravel’);
});
}

The results show that the test was passed displaying the result OK (1 test, 1 assertion)

Opening the file tests\Browser\ExampleTest.php will display for you the method above.

The browse method used accepts a callback that is an instance of the Browerclass. Within this callback, different methods and assertions that are unique to Dusk can be called.

Going to the visit() method allows you to run a test that visits the URL which matches with the argument specified. 

The assertSee()  method inspects to find if the text matching the argument provided appears on the page.

In the example given above a visit on the homepage is done plus a check for the appearance of the text ‘Laravel’. A look at the documentation page on laravel.com will show you that there are other assertions available that you can look into.

 

So how does a failed test look like?

Go to the argument assertSee() and replace the text ‘Laravel’ with text that does not appear on the visited page for example ‘whoa’. You will promptly get a failed test message. A screenshot of the failed test will also be available in the tests\Browser\screenshots directory.

Creating Browsers

To begin with, write a test that verifies application login. Upon generating a test, make a modification to navigate to the login page. Key in the necessary credentials and then click the ‘Login’ button.

Call on the browse method to create browser instance.

<?php

namespace Tests Browser;

use App \User;
use Tests\DuskTestCase;
use Laravel\Dusk\Chrome;
use Illuminate\Foundation\Testing\Database\Migrations;
class ExainpleTest extends DuskTestCase
{
use DatabaseMigrations;
/**

  • A basic browser test example.

  • @return void
    */
    public function testBasicExample()
    {
    $user - factory(User::class)->create{[
    'email' => '[email protected],com',
    ]);
    $this->browse (function (browser) use ($user) {
    $browser->visit('/login')
    ->type('email1j $user->email)
    ->type("password", "secret")
    ->press (' Login')
    ->assertPathIs('/home");
    });
    }
    }

From the example showcased above, it can be seen that the browse method does accept a callback.

This callback will automatically receive a browser instance from Dusk and through this instance interactions and assertions against the application will be made.

It is worth noting also that this test also can be used to test the make:auth  Artisan command generated login screen.

Multiple Browser Creation

It sometimes becomes necessary to have multiple browsers for proper testing to be done. An example of a chat screen that interacts with WebSockets may need testing on multiple browsers.

By going to the signature of the callback provided in the browse method and using “ask” for more than one browser you will be able to create multiple browsers.

$this->-browse(function ($first, $second) {
$first->loginAs( User::find(1))
->visit{'/home')
->waitForText ('Message');

$second-&gt;loginAs(User::find(2)) 
 -&gt;visit('/home') 
 -&gt;waitForText('Message')
 -&gt;type('Message', 'Hey Taylor') 
 -&gt;press('Send')

 $first-&gt;waitForText('Hey Taylor')
      -&gt;assertSee('Jeffrey Way');

});

Working with Authentication and Forms

Laravel Dusk allows you to interact with forms and authentication testing. To see this set up the basic Laravel login and registration forms. Begin by creating a database and update the .env file with information on the database. Now run.

   php artisan make:auth

This command results in the creation of migration and scaffolding files for authentication. Worth noting here is, in case you are running MYSQL that is lower than 5.7.7 or MariaDB you will have to go to the default string length in the boot method and edit the file setting app\Providers\AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringlength{l9l);
}

After this run;

php artisan migrate

This command generates database tables for you from the migration files. A visit to the homepage of your project will reveal the following along with the Login and Register Links on the far right corner.

Run the following command to create a new test named RegisterTest

   php artisan dusk:make RegisterTest

If you look at the tests\Browser folder you will see the file RegisterTest.php that will look like the snapshot below;

<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class RegisterTest extends DuskTestCase
{
/**

  • A Dusk test example.

*@return void
*/
public function testExample()
{
$this->browse(function (Jbrowser) {
$browser->visit('/')
->assertSee('Laravel');
});
}
}

Make changes to the testExample() method so that it looks similar to the image below;

public function testExample()
{
$this->browse(function ($browser) {
$browser->visit('/') //Go to the homepage
->clickLink('Register') //Click the Register link
->assertSee('Register') //Hake sure the phrase in

//Fill the form with these values
->value('#name','Joe')
->value('#email', '[email protected]')
->value('#password', '123456')
->value('#password-confirm', '123456')
->click('button[type="Submit"]') //Click the submit butt
->assertPathIs('/home')//Make sure you are in the home
//Make sure you see the phrase in the argument
->assertSee("You are logged in!");
}>;
}

After making customizations and edits to your command you may opt to get rid of the ExampleTest.php file which you no longer need.

   php artisan dusk:make RegisterTest

Some Final Thoughts

Laravel Dusk brings efficient and easy test writing to your fingertips. We have mentioned the key aspects of Laravel Dusk that you need to know about to get started. On the other side, Laravel Dusk still has plenty to it in relation to features. We shall delve more into the other features in forthcoming articles.



Laravel Development Company | Hire Laravel Developer

Laravel Development Company | Hire Laravel Developer

Get a free quote for custom Laravel Development Services from a trusted Laravel web development company. Hire Laravel Developers now @ best affordable rates

Get a free quote for custom Laravel Development Services from a trusted Laravel web development company. Hire Laravel Developers now at best affordable rates

Laravel Tutorial - Abusing Laravel

Laravel Tutorial - Abusing Laravel

Laravel Tutorial - Abusing Laravel: In this talk, Gustavo takes a look at the importance of Unit Tests and how Dependency Injection, which is often not promoted by Laravel docs, can help to achieve Unit Testing.

In this talk, Gustavo takes a look at the importance of Unit Tests and how Dependency Injection, which is often not promoted by Laravel docs, can help to achieve Unit Testing.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Laravel

Laravel 5.8 Tutorial for Beginners

Learn GraphQL with Laravel and Vue.js - Full Tutorial

Export or Import of CSV or Excel file in Laravel 5.8 with MySQL

Laravel 5.8 CRUD Tutorial With Example Step By Step

Build RESTful API In Laravel 5.8 Example

Laravel 6 Tutorial - How to make Auth in Laravel 6

Laravel 6 Tutorial - How to make Auth in Laravel 6

Are you looking for make Auth in Laravel 6 then I will help you to make Authentication using Laravel UI package in Laravel 6. I will explain to you how to create login and registration using Auth in Laravel 6.

Originally published at https://itsolutionstuff.com

Laravel 6 provide septate composer package for creating Auth scaffold in Laravel 6 application. Whenever you require to create auth in Laravel 6 then you must have to install Laravel/ui package in Laravel 6.

Using Laravel/ui you can create simple view with Auth as same you did before you do. But you have to use Vue.js or React.js with Auth view in Laravel 6. But they does not provide as default you have to follow few step to do Auth.

You have to follow few step to make auth in your Laravel 6 application.

First you need to install laravel/ui package as like bellow:

composer require laravel/ui

After that you can run following command and check ui commands info.

php artisan ui --help

Output:

Description:
  Swap the front-end scaffolding for the application
Usage:
  ui [options] [--] 
Arguments:
  type                   The preset type (bootstrap, vue, react)
Options:
      --auth             Install authentication UI scaffolding
      --option[=OPTION]  Pass an option to the preset command (multiple values allowed)
  -h, --help             Display this help message
  -q, --quiet            Do not output any message
  -V, --version          Display this application version
      --ansi             Force ANSI output
      --no-ansi          Disable ANSI output
  -n, --no-interaction   Do not ask any interactive question
      --env[=ENV]        The environment the command should run under
  -v|vv|vvv, --verbose   Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

You can use following commands for creating auth:

Using Vue:

php artisan ui vue --auth

Using React:

php artisan ui react --auth

Now you need to run npm command, otherwise you can not see better layout of login and register page.

Install NPM:

npm install

Run NPM:

npm run dev

Now you can run and check your app.

It will work great.

I hope it can help you....

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

Laravel 5.8 Tutorial for Beginners

What’s New in Laravel 6.0

Laravel 6 CRUD Application Tutorial

Laravel 6 Image Upload Tutorial