Laravel - 测试在中间件中创建独特的 cookie

Laravel - testing unique cookies creation in middlewares

我有一个为来宾用户创建 cookie 的中间件,我正在努力测试它。这是我的中间件的 handle 函数:


public function handle($request, Closure $next)
{
  $guestCookieKey = 'guest';

  if ($request->cookie($guestCookieKey)) {
    return $next($request);
  }

  return $next($request)->cookie($guestCookieKey, createGuestCookieId());
}

在浏览器上测试这个完美无缺:当请求没有这个 cookie 时,它​​会创建一个新的。当它确实有它时,我们只是转发请求链。

问题出在测试时。这是我正在做的事情:

namespace Tests\Feature;

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

class GuestCookieTest extends TestCase
{
  public function testItCreatesOnlyOneCookiePerResponse()
  {
    $firstResponse = $this->get('/');
    $secondResponse = $this->get('/');

    $this->assertEquals(
      $firstResponse->headers->getCookies()[0],
      $secondResponse->headers->getCookies()[0]
    );
  }
}

错误显示两个值之间的差异:

Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
 Symfony\Component\HttpFoundation\Cookie Object (
     'name' => 'guest'
-    'value' => 'eyJpdiI6IkttV2I2dldNelNkWXpyQXRWRUFlRUE9PSIsInZhbHVlIjoiQnBFYVlZNTNtYThjOWFxTTdLRXh4Zz09IiwibWFjIjoiZjY0NmEyNTMyMmM2MjJkNThmNmM5NWMxMDc2ZThmOTZjNDJhZTJjMmJhMGM0YTY0N2Q4NDg5YWEwNjI1ODEwZiJ9'
+    'value' => 'eyJpdiI6InRSMUVOSEZESm5xblwvOUU3aHQweGZ3PT0iLCJ2YWx1ZSI6ImhjU1lcL2pJUU1VbGxTN1BJQTdPWXBBPT0iLCJtYWMiOiJmM2QyYjQ3NzU5NWU5Nzk2Yjg0Yzg4MmFlNGFmYTdkNThlNjZhNzVhMjE3YjUxODhlNzRkMjA0MWQzZmEyODM2In0='
     'domain' => null
     'expire' => 0
     'path' => '/'

这就像 $this->get 不是在相同的环境中执行的 (?),没有保留之前设置的 cookie 并为每个调用创建唯一的调用和数据。这确实有道理,但是如果没有设置其他同名的 cookie,您将如何测试来宾 cookie 的创建?

尽管了解 E2E 测试和工具,但我不知道 Laravel Dusk 之类的东西解决了我的问题。

安装 Laravel Dusk 后,它会创建一个 tests/Browser 文件夹。

我只需要创建一个类似 GuestCookieTest.php 的测试文件,其中包含以下内容:

<?php

namespace Tests\Browser;

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

class GuestCookieTest extends DuskTestCase
{
    public function testItDoesNotOverwriteGuestCookieValue()
    {
        $this->browse(function (Browser $browser) {
            $firstCookieVal = $browser->visit('/')->cookie(config('guest'));
            $secondCookieVal = $browser->visit('/')->cookie(config('guest'));
            $this->assertEquals($firstCookieVal, $secondCookieVal);
        });
    }
}

绝对简单!