How does Laravel phpunit test assertion "$this->assertAuthenticatedAs($user, $guard = null)" work?

28 Views Asked by At

I am trying to test if a user is authenticated by using the "assertAuthenticatedAs" method. The method is fairly simple. It accepts the model instance and guard. But the following code will fail the test.

public function test_regsiter_a_user(): void
{
    $existingUsersCount = User::query()->count();
    $response = $this->postJson('/api/auth/register', [
        'email' => fake()->safeEmail(),
        'name' => fake()->firstName(),
        'password' => 'password',
        'password_confirmation' => 'password',
    ]);
    $this->assertDatabaseCount('users', $existingUsersCount + 1);
    $this->assertDatabaseCount('personal_access_tokens', 1);
    $response->assertCreated();
    $user = User::query()->where('email', $response->json()['user']['email'])->first();

    // $token = $response->json()['token'];
    // $this->getJson('api/user', headers: [
    //     'Authorization' => "Bearer $token"
    // ])->assertOk();

    $this->assertAuthenticatedAs($user, 'sanctum');
}

The strange thing is if I uncomment the code,

$token = $response->json()['token'];
$this->getJson('api/user', headers: [
        'Authorization' => "Bearer $token"
    ])->assertOk();

The assertion $this->assertAuthenticatedAs($user, 'sanctum'); will pass.

My controller's register method is the following.

public function register(Request $request)
    {
        $data = $request->validate([
            'email' => ['required', 'email', 'unique:users,email'],
            'name' => ['required'],
            'password' => ['required', 'confirmed'],
        ]);

        $user = User::query()->create($data)->fresh();

        $token = $user->createToken('email');

        return response()->json([
            'user' => $user,
            'token' => $token->plainTextToken,
        ], HttpStatus::CREATED->value);
    }

Can anyone explain this please?

0

There are 0 best solutions below