Request identifies as Inertia for API requests even though Middleware is called while testing
I have a middleware that converts Inertia responses to non-inertia Json. This middleware is attached to all API routes.
I did this so that I could have a single controller for both API and HTTP requests. It works perfectly when testing on the browser and using Postman.
However, when I run it using php artisan test the middleware runs but fails to detect that it's an API request.
This is how I identify if the request is API or Inertia:
// AppServiceProvider.php
public function boot(): void
{
$this->addIsApiMacroToRequest();
}
private function addIsApiMacroToRequest()
{
$request = app(Request::class);
$request->macro('isApi', function () use ($request) {
return $request->routeIs('api.*');
});
}
When running on the browser $request->isApi() returns false (as expected).
When running on postman $request->isApi() returns true (as expected).
When running via php artisan test, however, $request->isApi() returns false (it should return true).
My test case looks like this:
public function test_application_can_be_created(): void
{
$this->actingAs($user = User::factory()->withPersonalTeam()->create());
$response = $this->post(route('api.applications.store'), ['name' => 'Test Application']);
$this->assertDatabaseHas('applications', ['name' => 'Test Application']);
// Fails below because it returns Inertia response and not API Json response.
$response->assertJsonPath('name', 'Test Application');
$response->assertJsonPath('active', false);
}
This is how my middleware looks like:
class ParseApi
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
/**
* @var \Illuminate\Http\Response $response
*/
if($request->isApi())
{
$request->headers->set('Accept', 'application/json');
}
$response = $next($request);
if( $request->isApi()) {
return response()->json(
data: rescue(
callback: fn() => $response->original->getData()['page']['props'],
rescue: fn() => $response->original),
status: $response->status()
);
}
return $response;
}
}
Please or to participate in this conversation.