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 Test Case: Replace Illuminate\Foundation\Testing\TestCase with Laravel\BrowserKitTesting\TestCase in your Tests/TestCase.php:

    use Laravel\BrowserKitTesting\TestCase as BaseTestCase;
    
  3. First Test:

    public function testBasicPageLoad()
    {
        $this->visit('/')
             ->see('Welcome'); // Assert text exists
    }
    

Where to Look First

  • Core Methods: visit(), see(), dontSee(), click(), type(), press() (for forms).
  • JSON Testing: json(), seeJson(), seeJsonEquals(), seeJsonStructure().
  • Authentication: actingAs(), withSession().
  • Middleware: withoutMiddleware() trait/method.

First Use Case

Test a simple route with form submission:

public function testUserRegistration()
{
    $this->visit('/register')
         ->type('John Doe', 'name')
         ->press('Register')
         ->seePageIs('/dashboard');
}

Implementation Patterns

Common Workflows

1. Form Submission Testing

public function testLoginFlow()
{
    $this->visit('/login')
         ->type('user@example.com', 'email')
         ->type('password123', 'password')
         ->press('Login')
         ->seePageIs('/dashboard');
}

2. API Endpoint Testing

public function testCreateUserAPI()
{
    $this->json('POST', '/api/users', ['name' => 'Jane'])
         ->seeJsonEquals(['success' => true]);
}

3. Authentication Workflow

public function testProtectedRoute()
{
    $user = User::factory()->create();
    $this->actingAs($user)
         ->visit('/profile')
         ->see('Welcome, ' . $user->name);
}

4. Session Management

public function testSessionPersistence()
{
    $this->withSession(['theme' => 'dark'])
         ->visit('/')
         ->see('dark'); // Check if theme is applied
}

5. Middleware Isolation

public function testControllerWithoutMiddleware()
{
    $this->withoutMiddleware()
         ->visit('/admin')
         ->see('Unauthenticated Access'); // Bypass auth middleware
}

Integration Tips

  • Combine with Factories:
    $user = User::factory()->create();
    $this->actingAs($user)->visit('/profile');
    
  • Use refresh() for Dynamic Content:
    $this->visit('/dashboard')->refresh()->see('Updated Data');
    
  • Assert Redirects:
    $this->visit('/login')->seePageIs('/dashboard'); // After login
    
  • Test File Uploads:
    $this->visit('/upload')
         ->attach(__DIR__.'/test.jpg', 'avatar')
         ->press('Upload')
         ->see('Upload Successful');
    

Gotchas and Tips

Pitfalls

  1. Middleware Leaks:

    • Forgetting withoutMiddleware() can cause tests to fail if middleware (e.g., auth) isn’t handled.
    • Fix: Use WithoutMiddleware trait or withoutMiddleware() method.
  2. Session State:

    • Session data persists across tests unless cleared. Use withSession() carefully.
    • Fix: Reset sessions between tests or use refresh() to reload the page.
  3. Dynamic Content:

    • see()/dontSee() may fail if content is dynamically loaded (e.g., AJAX).
    • Fix: Use refresh() or wait for elements with sleep() (not ideal; prefer explicit waits).
  4. JSON Assertions:

    • seeJson() checks for partial matches, while seeJsonEquals() requires exact matches.
    • Fix: Use seeJsonStructure() for flexible structural validation.
  5. Route Caching:

    • Route names must match exactly (case-sensitive) in visitRoute().
    • Fix: Verify route names in routes/web.php.

Debugging Tips

  • Inspect Responses:
    $response = $this->call('GET', '/');
    dd($response->getContent()); // Debug raw HTML
    
  • Log Actions: Enable BrowserKit logging in phpunit.xml:
    <env name="BROWSERKIT_LOG" value="true"/>
    
  • Slow Tests: Add delays for AJAX-heavy pages:
    $this->visit('/')->sleep(2)->see('Dynamic Content');
    

Extension Points

  1. Custom Assertions: Extend TestCase to add domain-specific assertions:

    class CustomTestCase extends TestCase
    {
        public function seeErrorMessage($message)
        {
            return $this->see($message)->assertResponseStatus(422);
        }
    }
    
  2. Hooks for Setup/Teardown: Override setUp()/tearDown():

    protected function setUp(): void
    {
        parent::setUp();
        $this->withoutMiddleware();
    }
    
  3. Mocking External Services: Use Laravel’s HTTP clients or mocks with Mockery:

    $this->mock(Http::class)->shouldReceive('get')->andReturn(...);
    
  4. Custom Helpers: Add methods to TestCase for reusable test logic:

    public function loginAsAdmin()
    {
        $admin = User::factory()->admin()->create();
        $this->actingAs($admin);
    }
    

Config Quirks

  • Base URL: Override $baseUrl in TestCase if testing against a non-localhost environment:
    protected $baseUrl = 'https://staging.example.com';
    
  • CSRF Protection: BrowserKit automatically handles CSRF tokens for form submissions.
  • File Uploads: Paths in attach() are relative to the test’s working directory. Use absolute paths for reliability:
    $this->attach(__DIR__.'/../../storage/test.jpg', 'file');
    
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony