在Laravel中使用tymon / jwt-auth时如何测试注销?

时间:2019-05-10 19:44:46

标签: laravel unit-testing jwt-auth

我正在尝试使用tymon/jwt-auth软件包对我的api进行注销测试。在这里,我定义了api路由,控制器和单元测试。

api.php中:

Route::group(['middleware' => 'api', 'prefix' => 'auth'], function ($router) {
    Route::post('login', 'AuthController@login');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');

    Route::post('me/profile', 'AuthController@profile');
});

AuthController.php中:

/**
 * Log the user out (Invalidate the token).
 *
 * @return \Illuminate\Http\JsonResponse
 */
public function logout()
{
    auth()->logout();

    return response()->json(['message' => 'Successfully logged out']);
}

tests/Unit/AuthenticationTest.php中:

/**
 * Test if user can login trough internal api.
 *
 * @return void
 */
public function testLogin()
{
    $response = $this->post('api/auth/login', [
        'email' => 'admin@xscriptconnect.com',
        'password' => 'password'
    ]);

    $response->assertStatus(200)
        ->assertJsonStructure(['access_token', 'token_type', 'expires_in']);

    $this->assertAuthenticated('api');
}

/**
 * Test if user can logout trough internal api.
 *
 * @return void
 */
public function testLogout()
{
    $user = User::first();
    $user = $this->actingAs($user, 'api');

    $user->post('api/auth/logout')
        ->assertStatus(200)
        ->assertJsonStructure(['message']);

    $this->assertUnauthenticatedAs($user, 'api');
}

登录测试可以正常工作,但是在启动注销测试时,断言失败。它显示了此错误:

There was 1 failure:

1) Tests\Unit\AuthenticationTest::testLogout
Expected status code 200 but received 500.
Failed asserting that false is true.

当我使用此方法对其进行测试时:

public function testLogout()
{
    $user = User::first();
    $this->actingAs($user, 'api');

    $response = auth()->logout();
    $response->assertStatus(200);
    $response->assertJsonStructure(['message']);
}

我收到此错误:

There was 1 error:

1) Tests\Unit\AuthenticationTest::testLogout
Tymon\JWTAuth\Exceptions\JWTException: Token could not be parsed from the request

通过此软件包测试注销的正确方法是什么?请帮忙。

2 个答案:

答案 0 :(得分:0)

根据github页面中的this comment,我找到了解决此问题的方法。我这样更改了脚本,它可以正常工作。

/**
 * Test if user can logout trough internal api.
 *
 * @return void
 */
public function testLogout()
{
    $user = User::first();
    $token = \JWTAuth::fromUser($user);

    $this->post('api/auth/logout?token=' . $token)
        ->assertStatus(200)
        ->assertJsonStructure(['message']);

    $this->assertGuest('api');
}

如果有任何疑问,请随时发布有关该问题的其他答案。非常感谢。

答案 1 :(得分:0)

使用be()TestCase方法时,请覆盖actingAs()中的方法be()以设置授权标头

use Illuminate\Contracts\Auth\Authenticatable as UserContract;

abstract class TestCase extends BaseTestCase
{
    public function be(UserContract $user, $driver = null)
    {
        $token = auth()->fromUser($user);

        return parent::be($user, $driver)->withHeader('Authorization', "Bearer {$token}");
    }
}