1

I've built an api in Laravel 5.3 now I would like to test it. The api is using Tymen jwt-auth.

So for example the test for updating an account looks like this:

protected function headers($user = null) {
    $headers = ['Accept' => 'application/json'];
    if (!is_null($user)) {
        $token = JWTAuth::fromUser($user);
        JWTAuth::setToken($token);
        $headers['Authorization'] = 'Bearer '.$token;
    }
    return $headers;
}

/** @test */
public function a_user_updates_his_account() {
    factory(User::class)->create([
        'name' => 'Test',
        'last_name' => 'Test',
        'email' => 'mail@gmail.com',
        'mobile' => '062348383',
        'function' => 'ceo',
        'about' => 'About me.....',
        'corporation_id' => 1
    ]);

    $user = User::first();
    $user->active = 2;
    $user->save();

    $url = '/api/user/' . $user->slug;
    $test = $this->get($url, $this->headers($user));
    dd($test);
}

In the dd($test); I receive a internal server error back:

The token could not be parsed from the request

When I try this:

dd($this->headers($user));

This is the result:

"Accept" => "application/json"
"Authorization" => "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdCIsImlhdCI6MTQ4NDY0ODUxMiwiZXhwNDg0NjU5MzEyLCJuYmYiOjE0ODQ2NDg1MTIsImp0aSI6ImNhODBjZGZjZjI1YjdiYjM5ZGYxMTU4N2E0NmM1NTExIn0.IPKfabrad5RPtcyoNqwCHcDzMWPzFbLXdipvrBeVKZY"

So what could be wrong??

--EDIT--

If I put it in a middleware it's not working. But in a controller constructor it does?! Middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Request;

class TestingKeepRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ((\App::environment() == 'testing') && array_key_exists("HTTP_AUTHORIZATION", Request::server())) {
            JWTAuth::setRequest(\Route::getCurrentRequest());
        }

        return $next($request);
    }
}
Jamie
  • 10,302
  • 32
  • 103
  • 186

0 Answers0