Comments (3)
Thank you @denaje for the code. That helped a ton. Here is a slightly revised version that functions more like the parent call
method.
Extend the TestCase class with:
protected function createAuthenticatedUser()
{
$this->user = factory(App\Models\User::class, 'test')->create();
$this->token = JWTAuth::fromUser($this->user);
JWTAuth::setToken($this->token);
Auth::attempt(['username' => $this->user->username, 'password' => $this->user->password]);
}
protected function callAuthenticated($method, $uri, array $data = [], array $headers = [])
{
if ($this->token && !isset($headers['Authorization'])) {
$headers['Authorization'] = "Bearer: $this->token";
}
$server = $this->transformHeadersToServerVars($headers);
$this->call(strtoupper($method), $uri, $data, [], [], $server);
return $this;
}
Then use in tests like any other method:
public function testGetUser()
{
$this->createAuthenticatedUser();
$this->callAuthenticated('GET', route('auth::user'))->seeJsonStructure(['id']);
}
from jwt-auth.
Not OP, but here's how I did this in my code.
For most tests, I need to be logged in but I don't want to test auth, so I have this function in my base TestCase
class that logs in as a specific user that I call before running each test:
protected function login($user_id = 1)
{
$user = User::find($user_id);
$this->token = JWTAuth::fromUser($user);
JWTAuth::setToken($this->token);
Auth::login($user);
}
Every time I call a route, I then pass in the token in the headers:
protected function callRoute($method, $route, $data = [], $headers = [])
{
if ($this->token && !isset($headers['Authorization'])) {
$headers['HTTP_Authorization'] = "Bearer: $this->token";
}
return $this->call(
$method,
"/api$route",
[],
[],
[],
$headers,
json_encode($data)
);
}
For testing auth itself, I do this:
public function testLogin()
{
$this->seed('UserSeeder');
// callRoute's parameters: 1. Method 2. Url 3. Data 4. Headers
$resp = $this->callRoute('POST', '/auth', ['email' => '[email protected]', 'password' => 'password']);
$this->assertOk($resp);
// Get the token
$data = json_decode($resp->getContent(), true);
$this->assertArrayHasKey('token', $data);
// At this point, I could call another api endpoint and pass in the token. Something like this:
// $this->callRoute('POST', '/example', $data, ['HTTP_Authorization' => 'Bearer: ' . $data['token']]);
}
$this->callRoute
and $this->assertOk
are custom shortcut functions that I wrote to avoid lots of boilerplate.
from jwt-auth.
Hi. Did you managed to get your tests working ? I have the same problem and could use some help.
from jwt-auth.
Related Issues (20)
- How do we customise the claims? HOT 2
- Get All active tokens
- Method factory on JWTGuard not found
- setSecret method for custom JWT key is not working HOT 1
- Troubleshooting Issues with Laravel Tests and JWT Authentication HOT 2
- Examples for unmentioned routes (like Email Verification) HOT 1
- Followed the Laravel installation and quick start, getting error: "Tymon\\JWTAuth\\JWTGuard::login(): Argument #1 ($user) must be of type Tymon\\JWTAuth\\Contracts\\JWTSubject
- is possible use sap hana obdc with tymondesigns / jwt-auth ?
- Using a string instead of a file path for the `private` property in `jwt.php`.
- Clarification on Refresh Token Behaviour HOT 7
- attempt() never returns null, but returns blank booleans HOT 1
- Laravel 11 requires an update.
- Laravel 11 Compatibility needs nesbot/carbon ^3.0 HOT 1
- Random @deprecated docs
- Not authenticating api.php routes requests. HOT 3
- Wrong remaining minutes when blacklisting a token HOT 4
- Duplicate query to blacklisted tokens table
- Error when using the auth()->tokenById($id) function. HOT 1
- Redis connection to store blacklisted jwts HOT 1
- How does the jwt invlalidating works ? HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jwt-auth.