Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Browser Kit Testing Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require laravel/browser-kit-testing --dev
    
  2. Update Base TestCase: Replace Illuminate\Foundation\Testing\TestCase with Laravel\BrowserKitTesting\TestCase in your Tests/TestCase.php:
    use Laravel\BrowserKitTesting\TestCase as BaseTestCase;
    
  3. First Test: Use the fluent API to make a request and assert responses:
    public function test_homepage_loads()
    {
        $this->get('/')
             ->assertStatus(200)
             ->assertSee('Welcome');
    }
    

Where to Look First

  • Official Docs: Laravel BrowserKit Testing (check for latest updates).
  • TestCase Class: Review Laravel\BrowserKitTesting\TestCase for available methods (e.g., get(), post(), assert*()).
  • Example Tests: Browse Laravel’s core tests (e.g., tests/Feature/ExampleTest.php) for real-world usage.

Implementation Patterns

Core Workflows

  1. Basic Requests:

    $this->get('/dashboard')
         ->assertStatus(200)
         ->assertSee('Dashboard');
    
    • Chain methods for readability (e.g., get()->assert*()).
  2. Form Submission:

    $this->post('/login', [
        'email' => 'user@example.com',
        'password' => 'password123',
    ])
    ->assertRedirect('/dashboard');
    
  3. Session Persistence:

    $this->actingAs(User::find(1))
         ->get('/profile')
         ->assertSee('Welcome back!');
    
  4. CSRF Protection: Automatically handled via actingAs() or manual token inclusion:

    $this->post('/form', [
        '_token' => csrf_token(),
        'data' => 'value',
    ]);
    
  5. File Uploads:

    $this->post('/upload', [
        'file' => new \Illuminate\Http\UploadedFile(
            __DIR__.'/test.jpg',
            'test.jpg'
        ),
    ]);
    

Integration Tips

  • Middleware: Test middleware by calling withoutMiddleware() or withMiddleware():
    $this->withoutMiddleware()->get('/admin'); // Bypass auth
    
  • Service Providers: Register providers temporarily:
    $this->withProviders([\App\Providers\ExampleProvider::class])
         ->get('/endpoint');
    
  • Database Transactions: Use refreshDatabase() trait for isolated tests:
    use RefreshDatabase;
    

Gotchas and Tips

Pitfalls

  1. Session Conflicts:

    • Avoid shared sessions between tests unless intentional. Use actingAs() per test or clear sessions:
      $this->get('/logout')->assertRedirect('/');
      
    • Fix: Reset sessions between tests or use refreshDatabase() to wipe state.
  2. CSRF Token Mismatch:

    • If testing POST/PUT/DELETE routes, ensure CSRF tokens are included (handled automatically with actingAs() or from()).
  3. Base URL Mismatch:

    • Override $baseUrl in TestCase if testing a non-localhost environment:
      protected $baseUrl = 'https://staging.example.com';
      
  4. Assertion Order:

    • Chained assertions (e.g., 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');
      

Debugging

  • Dump Response:
    $response = $this->get('/debug');
    dd($response->getContent());
    
  • Enable Debugging: Set APP_DEBUG=true in .env.testing for detailed error logs.

Extension Points

  1. 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"
        );
    }
    
  2. 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'));
    });
    
  3. Headless Testing: Combine with laravel/pint or php-cs-fixer for static analysis in CI:

    ./vendor/bin/pint --test
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai