abdulrahmanhussin1024's avatar

Laravel AuthenticatedSessionControllerTest Fails with 404 for Login and Logout Tests

I am encountering an issue with testing the login and logout functionalities in my Laravel application. When I run the test suite, some tests fail with a 404 status code instead of the expected 401 or 200. Interestingly, when I run each test individually, they work perfectly fine. Below is my test code:

class AuthenticatedSessionControllerTest extends TestCase { use RefreshDatabase;

protected $user;

protected function setUp(): void
{
    parent::setUp();
    $this->withMiddleware([\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class]);

    $this->user = User::factory()->create([
        'email' => '[email protected]',
        'password' => bcrypt('password123'), // Ensure password matches login attempt
    ]);
}

#[Test] // Using PHPUnit 10+ attributes
public function user_can_login_with_valid_credentials()
{
    $response = $this->postJson('/api/v1/login', [
        'email' => $this->user->email,
        'password' => 'password123',
    ]);

    $response->assertStatus(200)
        ->assertJsonStructure([
            'success',
            'message',
            'data' => [
                'token',
            ],
        ]);
}

#[Test]
public function user_cannot_login_with_invalid_credentials()
{
    $response = $this->postJson('/api/v1/login', [
        'email' => $this->user->email,
        'password' => 'wrongpassword',
    ]);

    $response->assertStatus(401) // Expect 401 Unauthorized
        ->assertJson([
            'success' => false,
            'message' => 'These credentials do not match our records',
        ]);
}

#[Test]
public function user_can_logout()
{
    Sanctum::actingAs($this->user); // Authenticate the user

    $response = $this->postJson('/api/v1/logout');

    $response->assertStatus(200)
        ->assertJson([
            'success' => true,
            'message' => 'Successfully logged out',
        ]);
}

}

Running all tests together results in the following errors:

user_cannot_login_with_invalid_credentials Test: Fails with 404 instead of 401. user_can_logout Test: Fails with 404 instead of 200. When I run each test individually, they pass successfully.

What could be causing these tests to fail with 404 only when run together? Is there something I am missing with state handling in Laravel or Sanctum?

0 likes
4 replies
Jonjie's avatar

Can you show your api routes?

abdulrahmanhussin1024's avatar

@Jonjie

Route::middleware('guest:sanctum')->prefix('v1')->group(function () { Route::post('/login', [AuthenticatedSessionController::class, 'store']) ->name('login'); });

Route::middleware('auth:sanctum')->prefix('v1')->group(function () { Route::post('/logout', [AuthenticatedSessionController::class, 'logout']) ->name('logout'); });

Snapey's avatar

you are probably being logged in then redirected on subsequent tests

abdulrahmanhussin1024's avatar

@Snapey

Thank you for the insight! I suspected this as well but wasn’t sure how to ensure each test runs completely independently. Should I isolate each test into its own function, or is there a better approach? I’ve already tried using the RefreshDatabase trait and logging in explicitly in each test, but the issue persists. Would appreciate any guidance!

Please or to participate in this conversation.