laravel-5phpunitlaravel-5.5laravel-requestlaravel-response

Laravel 5.5 Testing JSON header doesn't work


I have a problem in testing Laravel 5.5. I need to send a Bearer Token in TEST HEADER, but doesn't work

public function testAuthCheckinvalidToken()
    {
        $response = $this->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $this->token,
        ])->json('GET', 'auth/check');
    ...
    }

When I dd($response), only the default HEADERS is set:

#headers: array:5 [
            "cache-control" => array:1 [
              0 => "no-cache, private"
            ]
            "date" => array:1 [
              0 => "Tue, 21 Nov 2017 18:48:27 GMT"
            ]
            "content-type" => array:1 [
              0 => "application/json"
            ]
            "x-ratelimit-limit" => array:1 [
              0 => 60
            ]
            "x-ratelimit-remaining" => array:1 [
              0 => 59
            ]
          ]

My HEADERS doesn't appear. I think that I am right


Solution

  • The headers you set here are for request obviously, for Response you are getting headers from your Laravel application so obviously you won't see the headers you set for your request.

    If you want to see headers you set here, you should run dd($request); in your app and not in tests.

    EDIT

    To confirm that headers are passed to application the whole testing code:

    tests/Feafure/ExampleTest.php

    <?php
    
    namespace Tests\Feature;
    
    use Tests\TestCase;
    
    class ExampleTest extends TestCase
    {
    
        public function testBasicTest()
        {
            $response = $this->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . 'abc',
            ])->json('GET', 'auth/check');
        }
    }
    

    routes/web.php

    Route::get('auth/check', function() {
       dd(request()->headers); 
    });
    

    so when I now run test:

    ./vendor/bin/phpunit
    

    result is:

    Symfony\Component\HttpFoundation\HeaderBag {#49   #headers: array:8 [
        "host" => array:1 [
          0 => "localhost"
        ]
        "user-agent" => array:1 [
          0 => "Symfony/3.X"
        ]
        "accept" => array:1 [
          0 => "application/json"
        ]
        "accept-language" => array:1 [
          0 => "en-us,en;q=0.5"
        ]
        "accept-charset" => array:1 [
          0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
        ]
        "content-type" => array:1 [
          0 => "application/json"
        ]
        "authorization" => array:1 [
          0 => "Bearer abc"
        ]
        "content-length" => array:1 [
          0 => 2
        ]   ]   #cacheControl: [] }
    

    so as you see headers from test are passed to application