Skip to content

Instantly share code, notes, and snippets.

@Rhincodon
Created August 9, 2017 14:22
Show Gist options
  • Save Rhincodon/93b27a5f4612dd4d848e7c74071b89b1 to your computer and use it in GitHub Desktop.
Save Rhincodon/93b27a5f4612dd4d848e7c74071b89b1 to your computer and use it in GitHub Desktop.
JWT TestCase
<?php
namespace Tests\Feature;
use App\User;
use Tests\JwtTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class JwtLoginTest extends JwtTestCase
{
use DatabaseTransactions, DatabaseMigrations;
protected $jwtTestUrl;
public function setUp()
{
parent::setUp();
$this->jwtTestUrl = route('api.jwt-test');
}
/**
* @test
*/
public function user_can_access_to_jwt_routes_with_token()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)->json('GET', $this->jwtTestUrl);
$response->assertStatus(200);
}
}
<?php
namespace Tests;
use Illuminate\Contracts\Auth\Authenticatable;
class JwtTestCase extends TestCase
{
protected $user;
/**
* @param Authenticatable $user
* @param null $driver
* @return $this
*/
public function actingAs(Authenticatable $user, $driver = null)
{
$this->user = $user;
return $this;
}
/**
* Call the given URI and return the Response.
*
* @param string $method
* @param string $uri
* @param array $parameters
* @param array $cookies
* @param array $files
* @param array $server
* @param string $content
* @return \Illuminate\Http\Response
*/
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
if ($this->user) {
$server['HTTP_AUTHORIZATION'] = 'Bearer ' . \JWTAuth::fromUser($this->user);
}
$server['HTTP_ACCEPT'] = 'application/json';
return parent::call($method, $uri, $parameters, $cookies, $files, $server, $content);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment