【问题标题】:Request header not set in test测试中未设置请求标头
【发布时间】:2020-07-08 10:40:31
【问题描述】:

我有一个尝试登录并获取详细信息的测试。我需要在此操作的请求标头中传递一个不记名令牌。请看下面的代码。我可以看到标题很少有我设置的标题。谁能给我指点来解决这个问题?

我正在使用 Laravel 7.2.2、PHP 7.4,

我正在运行 php artisan 测试

代码:

public function a_user_can_get_details()
    {
        $this->create_user();

        $response = $this->json('POST', 
                    '/api/login', 
                    [
                        "email" => "john.doe@example.com",
                        "password" => "john123"
                    ]);
        $response->assertSuccessful();

        $token = Str::replaceLast('"', '', Str::replaceFirst('"', '', $response->getContent()));
        $headers = [
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Bearer ' . $token
                    ];


        $response = $this->withHeaders($headers)
                        ->get('api/user');

        $response->assertSuccessful();
        $this->assertCount(1, User::all());

    }

这是我得到的错误。实际上,测试必须通过。那就是正确的用户名和密码:

Response status code [403] is not a successful status code. Failed asserting that false is true.

  at tests/Feature/UserTest.php:141
    137|
    138|         $response = $this->withHeaders($headers)
    139|                         ->get('api/user');
    140|
  > 141|         $response->assertSuccessful();
    142|         $this->assertCount(1, User::all());
    143|
    144|     }
    145|

【问题讨论】:

  • 您是否可以在create_user 函数上登录用户?
  • 我没有在 create_user 中登录。 private function create_user(){ return $this->post('/api/user', [ "name" => "John Doe", "email" => "john.doe@example.com", "password" => "john123", "password_confirmation" => "john123" ]); }
  • 你们有中间件吗?由于您收到 403,我认为这是由中间件提供的权限错误。
  • 我正在使用 sanctum 进行身份验证。除了默认的中间件 + sanctum + spatie 权限外,没有其他中间件在起作用。此外,我发现字符串操作存在问题。我改变了那个。现在我得到 401。下面是具有标题的 dd 摘录:` #headers: array:3 [ "cache-control" => array:1 [ 0 => "no-cache, private" ] "date" = > 数组:1 [ 0 => “星期六,2020 年 3 月 28 日 03:05:31 GMT”] “内容类型” => 数组:1 [ 0 => “应用程序/json”] `

标签: php laravel unit-testing


【解决方案1】:

我解决了这个问题。

原因:我在 Spatie Permissions 中添加了一个中间件条件来检查该特定路由的权限。我必须删除它才能使其正常工作。

取而代之的是,我现在检查用户的登录状态。这样就可以命中路线并在路线内完成所需的检查。

感谢所有帮助我解决这个问题的问题/cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多