laravel/browser-kit-testing
Fluent BrowserKit-style testing for Laravel apps: make HTTP requests, navigate pages, assert response content, and interact with forms in functional tests. Install as a dev dependency and extend Laravel\BrowserKitTesting\TestCase to get started.
composer require laravel/browser-kit-testing --dev
Illuminate\Foundation\Testing\TestCase with Laravel\BrowserKitTesting\TestCase in your Tests/TestCase.php:
use Laravel\BrowserKitTesting\TestCase as BaseTestCase;
public function test_homepage_loads()
{
$this->get('/')
->assertStatus(200)
->assertSee('Welcome');
}
Laravel\BrowserKitTesting\TestCase for available methods (e.g., get(), post(), assert*()).tests/Feature/ExampleTest.php) for real-world usage.Basic Requests:
$this->get('/dashboard')
->assertStatus(200)
->assertSee('Dashboard');
get()->assert*()).Form Submission:
$this->post('/login', [
'email' => 'user@example.com',
'password' => 'password123',
])
->assertRedirect('/dashboard');
Session Persistence:
$this->actingAs(User::find(1))
->get('/profile')
->assertSee('Welcome back!');
CSRF Protection:
Automatically handled via actingAs() or manual token inclusion:
$this->post('/form', [
'_token' => csrf_token(),
'data' => 'value',
]);
File Uploads:
$this->post('/upload', [
'file' => new \Illuminate\Http\UploadedFile(
__DIR__.'/test.jpg',
'test.jpg'
),
]);
withoutMiddleware() or withMiddleware():
$this->withoutMiddleware()->get('/admin'); // Bypass auth
$this->withProviders([\App\Providers\ExampleProvider::class])
->get('/endpoint');
refreshDatabase() trait for isolated tests:
use RefreshDatabase;
Session Conflicts:
actingAs() per test or clear sessions:
$this->get('/logout')->assertRedirect('/');
refreshDatabase() to wipe state.CSRF Token Mismatch:
actingAs() or from()).Base URL Mismatch:
$baseUrl in TestCase if testing a non-localhost environment:
protected $baseUrl = 'https://staging.example.com';
Assertion Order:
assertStatus()->assertSee()) fail silently if earlier assertions pass but later ones fail. Use expect() for explicit expectations:
$this->get('/page')->expect($this)
->assertStatus(200)
->assertSee('Content');
$response = $this->get('/debug');
dd($response->getContent());
APP_DEBUG=true in .env.testing for detailed error logs.Custom Assertions:
Extend TestCase to add domain-specific assertions:
public function assertSeeInElement($text, $element = 'body')
{
$this->assertTrue(
$this->response->contains($text),
"Response did not contain '$text' in $element"
);
}
Mocking HTTP Clients:
Use Mockery or PHPUnit to stub external requests:
$this->mock(Http::class, function ($mock) {
$mock->shouldReceive('get')
->once()
->andReturn(response('Mocked response'));
});
Headless Testing:
Combine with laravel/pint or php-cs-fixer for static analysis in CI:
./vendor/bin/pint --test
How can I help you explore Laravel packages today?