Dzale
4 months ago
740
3
Testing

Laravel Sanctum - Unit tests for logout via token

Posted 4 months ago by Dzale

Hey guys, i've noticed a strange thing when writing unit tests for logout.

Method:

    public function destroy(): JsonResponse
    {
        auth()->user()->currentAccessToken()->delete();
 
        return response()->success();
    }

Test:

    public function endpoint_shouldReturn200()
    {
        factory(User::class)->create([
            'email' => '[email protected]',
            'password' => bcrypt('password')
        ]);
 
        $response = $this->postJson(
            '/api/auth/tokens',
            [
                'email' => '[email protected]',
                'password' => 'password',
                'device_name' => 'ios'
            ]
        ); // Issuing a token, expecting 201
 
        $response->assertStatus(201);
 
        $token = $response->getData()->data->token;
 
        $response = $this->deleteJson(
            '/api/auth/tokens',
            [],
            [
                'Authorization' => "Bearer $token"
            ]
        );
 
        $response->assertStatus(200);
        $response->assertExactJson([
            'message' => null,
            'data' => null
        ]);
    }

Response i get:

{"message":"Call to undefined method Laravel\Sanctum\TransientToken::delete()","errors":null}

Route actually works when you call it from Postman/Application, but test fails. Maybe i am doing something wrong ?

Please sign in or create an account to participate in this conversation.