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 Laravel Package

friends-of-behat/mink

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require --dev friends-of-behat/mink
    

    For Laravel, use require-dev to avoid production bloat.

  2. Basic Configuration In composer.json, define a mink section under extra:

    "extra": {
        "mink": {
            "default_session": "selenium2",
            "sessions": {
                "selenium2": {
                    "goutte": false,
                    "selenium": {
                        "wdf": true,
                        "browser": "chrome"
                    }
                }
            }
        }
    }
    
  3. First Use Case: Testing a Login Flow Create a FeatureContext class (e.g., tests/FeatureContext.php):

    use Behat\MinkExtension\Context\MinkContext;
    use FriendsOfBehat\Mink\Driver\Selenium2Driver;
    
    class FeatureContext extends MinkContext {
        public function __construct() {
            $this->useMinkSession('selenium2');
        }
    }
    

    Write a .feature file:

    Feature: Login
      Scenario: Successful login
        Given I am on "/login"
        When I fill in "email" with "user@example.com"
        And I fill in "password" with "secret"
        And I press "Submit"
        Then I should see "Welcome, User"
    

Implementation Patterns

Workflows

  1. Session Management

    • Use useMinkSession() in BeforeScenario hooks to switch contexts (e.g., selenium2 for JS, goutte for headless).
    • Example:
      $this->getSession()->start();
      $this->getSession()->switchToIFrame('iframe-id'); // For embedded content
      
  2. Laravel-Specific Integration

    • Kernel Binding: Bind Mink in AppServiceProvider:
      public function register() {
          $this->app->singleton(Mink::class, function ($app) {
              return new Mink(new \FriendsOfBehat\Mink\Session($app['mink.session']));
          });
      }
      
    • Route Testing: Use Mink to test API routes via HttpSession:
      $session = $this->getSession();
      $session->visit('/api/login');
      $response = $session->getPage()->getContent();
      
  3. Data-Driven Tests

    • Parameterize tests with Given/When steps:
      /**
       * @Given I am logged in as :user
       */
      public function iAmLoggedInAs($user) {
          $this->visit('/login');
          $this->fillField('email', $user['email']);
          $this->pressButton('Login');
      }
      
  4. Debugging Tools

    • Screenshots: Save visual feedback:
      $this->getSession()->getDriver()->takeScreenshot('screenshot.png');
      
    • Element Inspection: Log element details:
      $element = $this->getSession()->getPage()->find('css', '.error');
      $this->log((string) $element->getOuterHtml());
      

Gotchas and Tips

Pitfalls

  1. Session Initialization

    • Issue: SessionNotCreatedException if Selenium WebDriver isn’t running.
    • Fix: Start the server manually or use Docker:
      docker run -d -p 4444:4444 selenium/standalone-chrome
      
    • Laravel Tip: Add a php artisan mink:server command to manage the session lifecycle.
  2. Dynamic Content

    • Issue: ElementNotFoundException for AJAX-loaded content.
    • Fix: Use explicit waits:
      $this->getSession()->wait(5000, 1000, function () {
          return $this->getSession()->getPage()->find('css', '.dynamic-content') !== null;
      });
      
  3. Headless Mode

    • Issue: Chrome headless may fail silently.
    • Fix: Configure wdf (WebDriverFactory) explicitly:
      "selenium": {
          "wdf": {
              "host": "http://localhost",
              "port": 4444,
              "browser": "chrome",
              "desired_capabilities": {
                  "chromeOptions": {
                      "args": ["--headless", "--disable-gpu"]
                  }
              }
          }
      }
      
  4. Symfony Dependency

    • Issue: Mink expects Symfony components (e.g., HttpKernel).
    • Fix: Mock the kernel in Laravel tests:
      $kernel = new \Illuminate\Foundation\Application();
      $this->getSession()->setKernel($kernel);
      

Tips

  1. Custom Drivers

    • Extend Selenium2Driver for Laravel-specific needs:
      class LaravelSeleniumDriver extends Selenium2Driver {
          public function loginAs(User $user) {
              $this->visit('/login');
              $this->fillField('email', $user->email);
              $this->pressButton('Login');
          }
      }
      
  2. Performance

    • Reuse sessions across scenarios to avoid overhead:
      $this->getSession()->start(); // Once in @BeforeScenario
      
  3. CI/CD

    • Use goutte for fast, headless tests in CI:
      "sessions": {
          "goutte": {
              "goutte": { "guzzle_version": "~6.0" }
          }
      }
      
    • Fall back to selenium2 for JS-heavy features.
  4. Debugging

    • Enable Mink’s built-in logging:
      $this->getSession()->getDriver()->setLogLevel(\Monolog\Logger::DEBUG);
      
    • Use php artisan mink:debug (if available) to inspect sessions.
  5. Extension Points

    • Custom Steps: Create reusable step definitions:
      /**
       * @Given I am on the :page page
       */
      public function iAmOnThePage($page) {
          $this->visit(route($page));
      }
      
    • Hooks: Leverage BeforeScenario/AfterScenario for setup/teardown:
      /**
       * @BeforeScenario
       */
      public function ensureSession() {
          $this->getSession()->start();
      }
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware