2

我正在尝试使用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

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

4

2 回答 2

1

根据它的 github 页面中的这个评论,我找到了解决这个问题的方法。我像这样更改了我的脚本并且它有效。

/**
 * 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');
}

如果有的话,请随时发布有关此问题的另一个答案。非常感谢。

于 2019-05-10T20:00:14.387 回答
0

使用aka方法时覆盖be()您的方法以设置授权标头TestCaseactingAs()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}");
    }
}
于 2020-12-04T03:44:35.140 回答