yashan
yashan

Reputation: 177

How to get header values in laravel testing

This is how i get response in test Case

$response = $this->call('POST','/api/auth/login',['username'=>'xx','password'=>'xxx'], [/* cookies */], [/* files */], ['HTTP_ClientSecret' => 'xxxx']);

Then we can get response content by like this

$response->getContents()

i want to know how to get response header data ?

Upvotes: 5

Views: 8137

Answers (2)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41320

You don't really need to get it for the testing, you need to assert that it has expected values.

Say, you testing the throttle middleware, to be sure that no one can try too manycredit cards with your web store, that is your unit test:

    $route = route('payment');

    $iMax = 60;
    for ($i = 1; $i <= $iMax; $i++) {

        $response = $this->call('POST', $route, []);
        $response->assertHeader('x-ratelimit-limit', $iMax);
        $response->assertHeader('x-ratelimit-remaining', $iMax - $i);
        $response->assertRedirect();
        $response->assertStatus(302);
        $this->assertSame(iMax, $response->headers->get('x-ratelimit-limit'));
        $this->assertSame(iMax-$i, $response->headers->get('x-ratelimit-remaining'));
    }

    // log down headers if needed
    //\Log::debug($response->headers);

    $response = $this->call('POST', $route, []);
    $response->assertHeader('x-ratelimit-limit', $iMax);
    $response->assertHeader('x-ratelimit-remaining', 0);

    $response->assertStatus(429);

Upvotes: 0

Ivanka Todorova
Ivanka Todorova

Reputation: 10219

Do something like:

$response->headers->get('content-type');

or whatever you need. Also dd($response->headers); might be useful to you if you want to see what is in your response headers.

$this->call() returns Response which is extending Symfony's Response and headers is an object ResponseHeaderBag which has the following methods.

Upvotes: 10

Related Questions