Docs

JWT Auth Tests

When doing TDD, most of our tests would usually cover protected endpoints. Endpoints that require authentication. This repository provides test helpers for protected endpoints, without having to deal with manually sending the token.

Available methods

📘

The below methods have the same signature as Laravel's test helper methods (get, post, put, delete, call).

authUserGet()GET with authentication
authUserPost()POST with authentication
authUserPut()PUT with authentication
authUserDelete()DELETE with authentication
authUserCall()Custom method, cookies, files, server, etc.. with authentication

👍

You can access the current authenticated user (which is a model factory) using $this->getAuthUser() and the token using $this->getAuthUserToken(). They are available in /tests/TestCase.php.

Example

<?php

$api->group(['middleware' => 'api.auth'], function ($api) {

    $api->post('posts', 'PostsController@create');

});
<?php

class FavoritePostsTest extends TestCase
{
 public function testCreatingNewPost()
    {
        $post = factory(App\Post::class)->make();
      
        $this->authUserPost('/api/posts', ['name' => $post->name])
        ->seeApiSuccess()
        ->seeJsonObject('post')
        ->seeJsonKeyValueString('name', $post->name);
    }
  
  
}

Approach for multi-tenant applications

Say you have mentors and mentees on your platform. Wouldn't you love to have the following test helpers?

->mentorGet(), ->mentorPost(), ->menteeGet(), ->menteePut(), etc..

If you open TestCase.php, you can see that we're manually logging in the user by calling $this->setAuthUserToken(). This is where we create a factory of User.

Your approach would be to go through all of the authUser methods and variables and rename them to mentor, and then modify the setMentorToken (previously setAuthUserToken) to generate a factory of type user which is always a mentor:

 $mentor = factory(App\User::class)->create(['type' => 'mentor']);

And then do the same for the mentee.