4

I have a headless laravel instance connected to a SPA on a subdomain. As my first test, I want to see a 401 when trying retrieve user data from the api without being logged in. My api path is defined as the following:

Route::middleware('auth:sanctum')->get('/user', 'UserAccountController@get_profile');

I know a CSRF token is needed before a user can successfully connect to the application, but I'm unsure how to include that in my test process as shown below

public function testExample()
{
    $response = $this->get('/api/user');
    $response->assertStatus(401); //  getting a 500 instead
}

In the Sanctum testing portion of the documentation, I see the following method:

Sanctum::actingAs( factory(User::class)->create(), ['view-tasks'] );

The issue here for me is that I don't want to attempt to load this path as a user, I want to know how to simulate a client machine that has the token, but isn't logged in. Is this possible?

Shane
  • 4,921
  • 5
  • 37
  • 53

1 Answers1

0

As per "Nick" in the laravel slack chat, I needed to change the request to the following:

public function testExample()
{
    $response = $this->getJson('/api/user');
    $response->assertStatus(401);
}

The get() assumes you’re doing a normal request, whereas getJSON() handles the necessary header settings. This call returned the 401 in the same way I see in my application.

Further, the following could be used to test a hypothetical JSON response

$response->assertJson([
  "message" => "User Unauthorized"
]);
Shane
  • 4,921
  • 5
  • 37
  • 53