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

Mink Browserkit Driver Laravel Package

behat/mink-browserkit-driver

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install Dependencies

    composer require --dev behat/mink behat/mink-browserkit-driver symfony/browser-kit
    
    • Use --dev as this is a testing tool.
  2. Basic Configuration Create a tests/Feature/ExampleTest.php:

    use Behat\Mink\Mink;
    use Behat\Mink\Session;
    use Behat\Mink\Driver\BrowserKitDriver;
    use Symfony\Component\HttpKernel\Client;
    
    class ExampleTest extends \Tests\TestCase
    {
        public function testBrowserKitDriver()
        {
            $client = new Client($this->app); // Laravel's HTTP test client
            $driver = new BrowserKitDriver($client);
            $session = new Session($driver);
            $mink = new Mink(['default' => $session]);
    
            $page = $mink->getSession()->getPage();
            $page->open('/');
            $this->assertEquals('Home', $page->getTitle());
        }
    }
    
  3. First Use Case

    • Test static routes, middleware, or API endpoints without a full browser.
    • Validate HTML responses, links, and form submissions.

Implementation Patterns

Workflows

  1. Integration with Laravel’s HTTP Tests Extend Laravel’s HttpTestCase to reuse the Client:

    use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
    
    class MinkTestCase extends BaseTestCase
    {
        protected function createMinkSession()
        {
            $client = $this->createClient();
            $driver = new BrowserKitDriver($client);
            return new Session($driver);
        }
    }
    
  2. Reusable Mink Helper Methods Add to tests/TestCase.php:

    protected function mink()
    {
        static $mink;
        if (!$mink) {
            $mink = new Mink(['default' => $this->createMinkSession()]);
        }
        return $mink;
    }
    
    protected function visit($uri)
    {
        $this->mink()->getSession()->visit($uri);
    }
    
  3. Testing Forms and Submissions

    $page = $this->mink()->getSession()->getPage();
    $page->fillField('email', 'user@example.com');
    $page->pressButton('Login');
    $this->assertPathIs('/dashboard');
    
  4. Assertions

    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->elementExists('css', '.alert-success');
    

Integration Tips

  • Laravel Mix/Asset Handling: Use mix() helper in tests to generate URLs:
    $page->open(mix('js/app.js'));
    
  • Authentication: Reuse Laravel’s auth helpers:
    $this->actingAs(User::first());
    $this->visit('/profile');
    
  • Database Transactions: Wrap tests in transactions to avoid side effects:
    public function setUp(): void
    {
        parent::setUp();
        $this->withoutExceptionHandling();
        $this->artisan('migrate:fresh');
        $this->beginDatabaseTransaction();
    }
    

Gotchas and Tips

Pitfalls

  1. Session Management

    • BrowserKitDriver does not persist sessions between tests. Use Laravel’s actingAs() or manually set cookies:
      $session = $this->mink()->getSession();
      $session->setCookie(new Cookie('laravel_session', $this->app['session']->getId()));
      
    • Fix: Reset the Client between tests or use Laravel’s refreshApplication() in setUp().
  2. JavaScript Limitations

    • BrowserKitDriver does not execute JavaScript. Use Selenium or Laravel Dusk for JS-heavy apps.
    • Workaround: Test API endpoints or mock JS behavior with PHPUnit.
  3. CSRF Token Mismatches

    • BrowserKitDriver may fail if CSRF tokens are missing. Disable CSRF for tests in routes/web.php:
      Route::middleware('web')->group(function () {
          Route::middleware('guest')->group(function () {
              // Test routes here
          });
      });
      
    • Better: Use Laravel’s actingAs() with a user that has CSRF tokens pre-generated.
  4. Static Assets (CSS/JS)

    • If assets are not loading, ensure APP_URL is set and mix() is configured:
      putenv('APP_URL=http://localhost');
      

Debugging Tips

  1. Inspect Responses Dump the raw response:

    $response = $this->mink()->getSession()->getDriver()->getClient()->getResponse();
    dd($response->getContent());
    
  2. Enable Debug Mode Configure BrowserKitDriver to log requests:

    $client = new Client($this->app, [
        'debug' => true,
        'headers' => ['HTTP_ACCEPT' => 'text/html'],
    ]);
    
  3. Handle Redirects BrowserKitDriver follows redirects by default. Disable with:

    $client->followRedirects(false);
    

Extension Points

  1. Custom Middleware Attach middleware to the Client for testing:

    $client = new Client($this->app);
    $client->getKernel()->addMiddleware(new \App\Middleware\TestMiddleware());
    
  2. Mocking HTTP Requests Use Http::fake() alongside Mink:

    Http::fake();
    $this->visit('/api/data');
    Http::assertSent(function ($request) {
        return $request->hasHeader('Authorization');
    });
    
  3. Headless Testing Combine with Laravel’s HttpTestCase for hybrid tests:

    public function testHybrid()
    {
        $response = $this->get('/');
        $this->assertEquals(200, $response->status());
        // Use Mink for DOM assertions
        $this->visit('/');
        $this->assertSession()->elementExists('css', 'h1');
    }
    
  4. Parallel Testing BrowserKitDriver is not thread-safe. Run tests sequentially or use a separate Client per test class.

Config Quirks

  • Base URL: Set APP_URL in .env.testing or override in setUp():
    putenv('APP_URL=http://test.example.com');
    
  • Environment: Ensure APP_ENV=testing is set to avoid caching issues.
  • Session Driver: Use array or database session drivers for consistency:
    'session' => [
        'driver' => 'array',
    ],
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui