Detailed introduction of LaravelDusk browser testing is more elegant

Source: Internet
Author: User
When you use Laravel5.4 to start your application, LaravelDusk brings us an API for browser testing. it gives us a built-in ChromeDriver. of course, if other browsers want to use it, selenium can be used.] When your environment supports Laravel5.4, the first step is to install a demo. We use composer to install Laravel. when you start your application with a Laravel 5.4, laravel Dusk brings us an API for browser testing. it gives us a built-in ChromeDriver. of course, Selenium can be used for other browsers.] When your environment supports Laravel 5.4, the first step is to install a demo. We use composer to install Laravel.

composer create-project --prefer-dist laravel/laravel demo
Install Laravel Dusk
composer require laravel/dusk

This method is registered globally in Laravel. if you do not want to register globally, use method 2.

Method 2

In the installation environmentAppServiceProviderRegisterDuskServiceProvider

namespace App\Providers;use Illuminate\Support\ServiceProvider;use Laravel\Dusk\DuskServiceProvider;class AppServiceProvider extends ServiceProvider{    /**     * Register any application services.     *     * @return void     */    public function register()    {        if ($this->app->environment('local', 'testing', 'staging')) {                   $this->app->register(DuskServiceProvider::class);        }    }}

Next we will installDUSK#

php artisan dusk:install

 browse(function ($browser) {            $browser->visit('/')                    ->assertSee('Laravel');        });    }

Note: You need to log on. we have added a test user.

  • Add Test user

    1. execute the command to createUserTable

    php artisan migrate

    2. usetinkerCommand to add 10 pieces of test data

    php artisan tinkerfactory(App\User::class, 10)->create();

    Of course, we can also register by ourselves. The user name and password are required for testing.

    Email: moocfans@moocfans.cn
    Password: moocfans

    InLoginTestClass, add a test case to verify that the user has successfully logged on and returns to the welcome page.

        /** * A Dusk test example. * * @return void */public function test_I_can_login_successfully(){    $this->browse(function ($browser) {        $browser->visit('/login')                ->type('email', 'moocfans@moocfans.cn')                ->type('password', 'moocfans')                ->press('Login')                ->assertSee('You are logged in!');    });}

    Next let's start testing.

    php artisan dusk

    If your database has correct data, the following results will be returned.

Note that the chrome version must be later than 54.

Failed tests

We can deliberately modify an incorrect test case,PHPUnitError message. Change the logon password to 1.

public function test_I_can_login_successfully()    {        $this->browse(function ($browser) {            $browser->visit('/login')                    ->type('email', 'moocfans@moocfans.cn')                    ->type('password', '1')                    ->press('Login')                    ->assertSee('You are logged in!');        });    }

Then edit the test case

  class CreateTaskTest extends DuskTestCase{    /**     * A Dusk test example.     *     * @return void     */    public function test_I_can_create_task_successfully()    {        $this->browse(function ($browser) {            $browser->visit('/tasks/create')                    ->type('title', 'My Task')                    ->press('Add Task')                    ->pause(5000)                    ->assertPathIs('/tasks');        });    }}
  • Test case execution process

    1. enter the title
    2. click "Add Task ".
    3. wait for 5 seconds
    4. redirect to the task page

We can also usewaitUntilMissingTo executeDuskAPI

 browse(function ($browser) {            $browser->visit('/tasks/create')                    ->type('title', 'My Task')                    ->press('Add Task')                    ->waitUntilMissing('.btn-primary')                    ->assertPathIs('/tasks');        });    }}

For more APIs, see Laravel 5.4 Documentation.

Looking at another example #

Bind your logon EMail in the mode dialog box
The process of creating this test case.

Login
Find the Support Email link
Click Support Email
See your bound EMail
Based on the above process, we create a test case
First, createSupportEmailsTestTest cases

php artisan dusk:make SupportEmailsTest

Edit test cases

class SupportEmailsTest extends DuskTestCase{    /**     * A Dusk test example.     *     * @return void     */    public function test_I_can_open_modal_for_support_emails()    {        $this->browse(function ($browser) {            $user = factory(User::class)->create();            $browser->loginAs($user)                    ->visit('/tasks')                    ->clickLink('Support Email')                    ->whenAvailable('#modal-support', function ($modal) use($user) {                        $modal->assertInputValue('#support-from', $user->email);                    });        });    }}

Let's execute this test case.

php artisan dusk tests/Browser/SupportEmailsTest.php

urlNavigationDuskThe execution address.

public function assert(Browser $browser){    $browser->assertPathIs($this->url());}

Assert defines the assertions of the page. when CreateTaskPage is used, these assertions will be executed using the assert method.
In the above example, we just clarified that the Url is correct.

public function elements(){    return [        '@addTask' => '.btn-primary',    ];}

elementsThe selector can be defined. We can define program readable name selectors and reuse their web pages in different test cases. In the above example, I defined the selector for the add Task button.
Now let's ModifycreatetasktestClass and use the selector:

class CreateTaskTest extends DuskTestCase{    /**     * A Dusk test example.     *     * @return void     */    public function test_I_can_create_task_successfully()    {        $this->browse(function ($browser) {            $user = factory(User::class)->create();            $browser->loginAs($user)                    ->visit(new CreateTaskPage)                    ->type('title', 'My Task')                    ->click('@addTask')                    ->waitUntilMissing('@addTask')                    ->assertPathIs('/tasks');        });    }}

We have viewed the modification.createtaskpage. Now let's re-run our test to see if everything is normal:
This is the same as the test above, so I use the same image.

The above is a detailed description of the more elegant test details of Laravel Dusk browser. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.