Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send headers with phpunit api request?

I am trying to test my web service which is written in laravel 5 using phpunit. I am new to this testing framework. The application uses JWT for authentication which is passed in headers in the requests.

My test look likes so:

$response = $this->call('POST', 'authenticate', [
    'username' => 'carparts',
    'email' => '[email protected]',
    'password' => 'password'
]);

$token = 'Bearer ' . json_decode($response->getContent())->token;

$response = $this->call('POST', 'users', [
    "first_name"    => "Test",
    "last_name"     => "Test",
    "email"         => '[email protected]',
    "password"      => "testing",
    "role"          => "1"
], [], [], [
    'Authorization' => $token
]);

dd($response->getContent());

The token is returned fine but when I try to use in the next request to create a new user, it fails saying the token could not parsed from the request. When I do request()->headers in a middleware to check, even that does not show the header. What am I doing wrong? How to pass headers in a request using PHPUnit?

like image 788
Rohan Avatar asked Nov 09 '22 23:11

Rohan


1 Answers

There's a function to translate headers to server vars. Try passing this instead:

$this->transformHeadersToServerVars([ 'Authorization' => $token ])
like image 117
David Avatar answered Nov 14 '22 22:11

David