N
N
NikolayAlb2018-10-09 16:29:25
PHPUnit
NikolayAlb, 2018-10-09 16:29:25

How to test the page where the browser receives cookies?

Good afternoon, there is a simple localization logic on the site:
A controller with a route, to which the user goes to set the language:

Route::get('lang/{lang}', ['uses'=>'[email protected]'])->name('lang.set');

public function setLang($lang)
    {
        if (array_key_exists($lang, config('languages'))) {
            setcookie ('applocale', $lang, 0, '/', NULL, 0 );
        }
        return redirect()->back();
    }

There is also a global middleware that hangs on any request and determines the display language using cookies:
public function handle($request, Closure $next)
    {
        $requestedLocale = $request->cookie('applocale');
        $applocale = config('app.locale'); // default locale

        if( $requestedLocale !== null && array_key_exists($requestedLocale, config('languages'))) {
             $applocale = $requestedLocale;
        }

        app()->setLocale($applocale);
        session()->put('applocale', $applocale);
        Carbon::setLocale($applocale);

        return $next($request);
    }

I'm trying to write a test to check if this cookie is set:
/**
     * Language can be changed.
     *
     * @return void
     *
     * @runInSeparateProcess
     */
    public function testChangeLanguage()
    {
        print 'Locale before: ' . app()->getLocale() . "\n";
        $this->get('/lang/en')->assertStatus(302);
        print 'Locale after:  ' . app()->getLocale();
        $this->get('/')->assertCookie('applocale');
    }

But as a result, phpunit throws an error:
Cookie [applocale] not present on response.
Failed asserting that null is not null.
 C:\...\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:154
 C:\...\tests\Feature\LanguageTest.php:24
 
Locale before: ru
Locale after:  ru

How to test it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2018-10-09
@NikolayAlb

there are no cookies in the console, so there is no point in testing them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question