Can you show your api routes?
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?
Please or to participate in this conversation.