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: make HTTP requests, follow routes, fill forms, and assert response content with simple methods like visit, see, and dontSee. Install as a dev dependency and extend Laravel\BrowserKitTesting\TestCase.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  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: Write a simple test to verify a page loads and contains expected text:
    public function test_homepage_loads()
    {
        $this->visit('/')
             ->see('Welcome');
    }
    

Key Starting Points

  • BrowserKit API: Methods like visit(), see(), click(), and type() are chainable for fluent testing.
  • JSON API Testing: Use json(), seeJson(), and seeJsonStructure() for API endpoints.
  • Authentication: Leverage actingAs() for testing authenticated routes.

Implementation Patterns

Common Workflows

  1. Form Submission Testing:

    public function test_user_registration()
    {
        $this->visit('/register')
             ->type('John Doe', 'name')
             ->type('john@example.com', 'email')
             ->check('terms')
             ->press('Register')
             ->seePageIs('/dashboard');
    }
    
  2. API Contract Testing:

    public function test_create_user_api()
    {
        $this->json('POST', '/api/users', ['name' => 'Jane'])
             ->seeJsonStructure(['id', 'name', 'created_at'])
             ->assertResponseStatus(201);
    }
    
  3. Session/State Testing:

    public function test_session_persistence()
    {
        $this->withSession(['theme' => 'dark'])
             ->visit('/dashboard')
             ->see('Dark Theme');
    }
    
  4. Middleware Isolation:

    public function test_route_without_middleware()
    {
        $this->withoutMiddleware()
             ->visit('/admin')
             ->see('Unauthenticated Access');
    }
    

Integration Tips

  • Combine with Factories: Use Laravel's factories to create test users/data:
    $user = User::factory()->create();
    $this->actingAs($user)->visit('/profile');
    
  • Custom Assertions: Extend the test case for reusable assertions:
    protected function assertFlashMessageContains($message)
    {
        $this->see($message);
    }
    
  • Headless Testing: Use laravel/browser-kit-testing alongside laravel/dusk for browser automation when needed.

Gotchas and Tips

Pitfalls

  1. Middleware Leaks: Forgetting to disable middleware (e.g., auth) can cause tests to fail unexpectedly. Use withoutMiddleware() or the WithoutMiddleware trait.

    // ❌ Fails if route requires auth
    $this->visit('/admin');
    
    // ✅ Works
    $this->withoutMiddleware()->visit('/admin');
    
  2. Session State Pollution: Shared test state (e.g., session data) can cause flaky tests. Reset state between tests:

    public function tearDown(): void
    {
        $this->withSession([]); // Clear session
        parent::tearDown();
    }
    
  3. Dynamic Routes: Named routes with parameters require exact matching:

    // ❌ Fails if route expects `user` param
    $this->visitRoute('profile');
    
    // ✅ Works
    $this->visitRoute('profile', ['user' => 1]);
    
  4. File Uploads: Paths in attach() must be absolute or resolved correctly:

    // ❌ Fails if path is relative
    $this->attach('test.jpg', 'avatar');
    
    // ✅ Works
    $this->attach(public_path('test.jpg'), 'avatar');
    

Debugging Tips

  • Inspect Responses: Use dump($this->response->getContent()) to debug HTML/JSON responses.
  • Log Requests: Enable Laravel's debug mode (APP_DEBUG=true) to log requests in the terminal.
  • Slow Tests: BrowserKit can be slow for complex interactions. Optimize by:
    • Avoiding DatabaseTransactions if not needed.
    • Using DatabaseMigrations for large datasets.

Extension Points

  1. Custom Matchers: Extend the test case to add domain-specific assertions:

    public function seeUserName($name)
    {
        $this->see('Welcome, '.$name);
    }
    
  2. Hooks for Setup/Teardown: Override setUp() and tearDown() for shared test logic:

    protected function setUp(): void
    {
        parent::setUp();
        $this->actingAs(User::factory()->create());
    }
    
  3. Mocking External Services: Use Laravel's HTTP clients or mocks to isolate tests:

    $this->mock(Http::class)->shouldReceive('post')->once();
    
  4. Parallel Testing: BrowserKit tests are not inherently parallelizable due to session state. Use pestphp/pest or PHPUnit's --parallel with caution.


```markdown
---
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport