Jwt-auth: How to mock authentication in kernel?

Created on 15 Jun 2016  路  6Comments  路  Source: tymondesigns/jwt-auth

I'm trying to write some unit tests which do not actually test authentication itself.

Is there an easy way to mock the auth guard to make it pass or fail or ideally act as a specific authenticated user?

I really just want the following to work:

$this->actingAs($user)->call(....)

Most helpful comment

@timbroder Thanks, I do the same thing as well. I often find that integration tests are more useful for controller testing than unit tests... might just be me but I find I'm hardly testing anything when I do unit tests on controllers.

All 6 comments

Sorry I'm not understanding exactly where the problem is. Does that code _fail_, or are you hitting other issues?

If you're having issues hitting the middleware, you can just turn it all off in your tests with use WithoutMiddleware; or $this->withoutMiddleware();.

If you really need finer grained control, you can mock the facade for JWTAuth. But exactly which methods you'll need to support will depend on your version & your needs.

Hi @tdhsmith,

I'm trying to make the JWTAuth in the middleware pass authentication so I can unit test some controller methods which require a token.

With normal authentication, I can use Laravel's built in "actingAs" method to authenticate as a specific user.

Is there a good way to do this with JWTAuth? If I turn off middleware then I feel like that will be the same thing as taking the endpoint out of the guarded route?

Do you have any code samples showing how I could go about unit testing the logic within controller method without actually testing the JWTAuth?

@andreliem I handle this in my integration tests by retrieving a user from the db in my test's setUp and then using that token.

You are talking about Unit Tests so this feels dirty, but might be a good temporary workaround

@timbroder Thanks, I do the same thing as well. I often find that integration tests are more useful for controller testing than unit tests... might just be me but I find I'm hardly testing anything when I do unit tests on controllers.

I know this is closed, but just wanted to add my 2cents.

This is how I resolved the actingAs in order to use it with jwt-auth.

https://gist.github.com/MartinPeverelli/73408c62c856897531950333ca378db4

Then, in a test, I can simply do as usual:

$response = $this->actingAs($user)
    ->patch('/api/profile/update/'.$user->id, [
         'name'  => 'bar',
         'email' => '[email protected]',
    ]);

Hope it helps!

@andreliem agree with you 100% there (sorry missed the notification for your message)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gandra picture gandra  路  3Comments

therealmjk picture therealmjk  路  3Comments

johncloud200 picture johncloud200  路  3Comments

harveyslash picture harveyslash  路  3Comments

phamduong picture phamduong  路  3Comments