Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Last active February 12, 2025 18:08
Show Gist options
  • Save DominikStyp/a7b824ad55796297583a73a2b1f3bbe6 to your computer and use it in GitHub Desktop.
Save DominikStyp/a7b824ad55796297583a73a2b1f3bbe6 to your computer and use it in GitHub Desktop.
Laravel: Mock the request for view test
<?php
use Illuminate\Support\Facades\Request;
use Mockery as m;
use Tests\TestCase;
// this is solving the static calls for the route like:
// @if(Request::route()->getName() == 'admin.report') ........
// <li class="{{Request::is('*/admin/conversion*') ? 'active' : null }}"> .........
//
// one can mock those and test the view content only with data
private function mockRequestForView(): void
{
$mockRequest = m::mock(\Illuminate\Http\Request::class);
$mockRequest->shouldReceive('route')->andReturnUsing(function () {
$mockRoute = m::mock(\Illuminate\Routing\Route::class);
$mockRoute->shouldReceive('getName')->andReturn('example.route.name');
return $mockRoute;
});
$mockRequest->shouldReceive('setUserResolver')->andReturnNull();
$mockRequest->shouldReceive('getUserResolver')->andReturnNull();
$mockRequest->shouldReceive('root')->andReturn('http://localhost');
$mockRequest->shouldReceive('routeIs')->andReturn(false);
$mockRequest->shouldReceive('is')->andReturn(false);
$mockRequest->shouldReceive('cookie')->andReturn(null);
$mockRequest->shouldReceive('getPathInfo')->andReturn('/path');
Request::swap($mockRequest);
}
public function view_test()
{
$this->actingAs(
User::where('username', 'admin')->first()
);
$this->mockRequestForView();
$response = $this->view('management.users.detail', [
'user' => [ 'name' => 'testuser' ]
]);
$response->assertSee('testuser');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment