我正在尝试使用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
通过这个包测试注销的正确方法是什么?请帮忙。