Last active
February 12, 2025 18:08
-
-
Save DominikStyp/a7b824ad55796297583a73a2b1f3bbe6 to your computer and use it in GitHub Desktop.
Laravel: Mock the request for view test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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