Laravel Test live examples laravelの試験例

Laravel Test live examples laravelの試験例

I’ve been working on migrating a legacy laravel 4.2 project to Laravel 7.2 recently. And I’ve written some feature test cases and artisan command test cases as well as laravel dusk tests. Below are sample codes I have written. People who are interested in Laravel TDD can use following test case snippet code as templates. Have fun using TDD~

Laravel Dusk test:

DuskTestCase.php

<?php

namespace Tests;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\TestCase as BaseTestCase;

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        $options = (new ChromeOptions)->addArguments([
            '--disable-gpu',
            '--headless',
            '--window-size=1920,1080',
            '--no-sandbox',
        ]);

        return RemoteWebDriver::create(
            'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY, $options
            )
        );
    }
}


LoginTest.php

<?php

namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class LoginTest extends DuskTestCase
{
    /**
     * @group CanShowLoginPage
     */
    public function testCanShowLoginPage()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/HokHyk/login')
                ->dump()
                ->assertSee('Login');
        });
    }
}

php artisan dusk --group CanLogin

If you meet the following error, do not panic.


There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"capabilities":{"firstMatch":[{"browserName":"chrome","goog:chromeOptions":{"binary":"","args":["--disable-gpu","--headless","--window-size=1920,1080"]}}]},"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"binary":"","args":["--disable-gpu","--headless","--window-size=1920,1080"]}}}

Failed to connect to 127.0.0.1 port 10000: Connection refused

Installing Laravel Dusk - Failed to connect on localhost port 9515: connection refused

To solve this problem , just add --no-sandbox.

protected function driver()
    {
        $options = (new ChromeOptions)->addArguments([
            '--disable-gpu',
            '--headless',
            '--window-size=1920,1080',
            '--no-sandbox',
        ]);

Laravel Artisan command test:

<?php

namespace Tests\Feature\ArtisanComands;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;

class ExportTest extends TestCase
{
    public function it_has_exportAll_command()
    {
        $this->assertTrue(class_exists(\exportAll::class));
    }
    /**
     * @group ExportAll
     */
    public function testExportAllCommand()
    {
        $this->withoutExceptionHandling();

        // 1. arrange
        $running_jobs = \Job::where('status', 'running')->get();
        Foreach($running_jobs as $job)
        {
            $job->status = "queueing";
            $job->save();
        }
        
        // 2. act
        Artisan::call('exportAll', []);
        // If you need result of console output
        $resultAsText = Artisan::output();
        dd($resultAsText);

        // 3. assert
//        $this->assertRegExp("", $resultAsText->get);
        $this->artisan('exportAll')
            ->assertExitCode(0);
    }
}

Laravel Feature test:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class v3GetSubmissionsListingTest extends TestCase
{
    /**
     * @group CanSubmit
     */
    public function testCanGetSubmissionList()
    {
        $this->withoutExceptionHandling();

        $clientId = 'XXX';
        $submissionId = '24';
        $api_url = "api/v1/submit/listing/{$clientId}";

        $server = [
            'user-agent' => 'PostmanRuntime/7.26.1',
            'x-forms-signature' => 'D23C49789FD91E3831EB1',
            'x-forms-token' => 'do7rG7uWpslfYHdS2r',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];

        $data = [
            'option' => '{"start":"2019-01-01","end":"2020-07-31"}',
            'formId' => '12489810',
            'skip' => 5,
        ];

        $cookies = [
            '__HOK-SESSION-HYK__' => 'eyJpdiI6IjJqMUVlMVgwL2ZSYURaMGEwIn0=',
        ];

        $session = [
            "_HOK_HYK" => [
//                "_HOK_USER_ID" => "02d20a3f-2e06-450f-aa37-c2e201b8fd4f",
                "_HOK_COMPANY_ID" => 100,
                "_HOK_USER_EMAIL" => "[email protected]",
                "_HOK_PERMISSION" => "N",
                "_HOK_USER_GROUPS" => [],
            ]
        ];

        $response = $this
            ->disableCookieEncryption()
            ->withCookies($cookies)
            ->withSession($session)
            ->withHeaders($server)
            ->post($api_url, $data, $server)
            ->dump()
            ->assertStatus(200)
            ->assertJsonStructure([
                    "status" =>  [
                        "error_no",
                        "error_msg"
                    ],
                    "data" => [
                        "submitlist" => [
                            '*' => [
                                "id",
                                "UserId",
                                "EditorId",
                                "FormsId",
                                "viewAnswersLinkData" => [
                                    "title",
                                    "content-type",
                                    "reload-previous-view",
                                ],
                                "columns" => ['*' => []],
                                "column_types" => [
//                                    "0" => "form-title",
//                                    "1" => "title",
//                                    "2" => "progress",
//                                    "3" => "submitter",
//                                    "4" => "notify",
//                                    "5" => "reference",
                                ],
                            ],
                        ],
                        "refineCount",
                        "showReferenceFlg",
                        "viewReportPermission",
                        "auto_refine_info",
                    ],
            ]);
    }
}

I want to point out that here for Feature test , you can setup your cookie, session and request data by using this template easily. To get the actual cookie and session info you can use psotman’s interceptor to get them or , by dd(request()->session()->all()) or dd(request()->cookie()) to get all cookies.

The best place to get them is to dd() inside a middleware’s handle() method. e.g. EncryptCookies.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.