Search code examples
behatgoogle-chrome-headlessmink

How do I fix the browser window size in Behat 3 / Mink?


I want to run all my Behat/mink tests at a mobile display resolution. What would be really nice is to run all the tests with Chrome in dev tools mode where you can select "iPhone 5/SE" and so on to get a simulation of running on that device.

So, I tried to implement something like this myself by setting the display resolution in FeatureContext.

Here's an SO question on how to resize browser windows with Behat 2. And there's sample code for setting the window resolution in Behat/Mink/Drupal.

Based on these examples, I added the following code to my FeatureContext:

  /**
   * @BeforeScenario
   */
  public function resizeWindow()
  {
    $this->getSession()->resizeWindow(100, 500, 'current');
  }

However, I'm getting this error:

Fatal error: Call to a member function window() on null (Behat\Testwork\Call\Exception\FatalThrowableError)

I also tried:

  • Using BeforeStep instead of BeforeScenario (result: same error)
  • Adding a step "I set the resolution to A x B" (result: I can resize the window in tests this way, but when I submit a form in a test, the screen resolution is reset; to fix this, I can add the step to set the resolution after each other step, but that is very inefficient)
  • I tried setting the window size as a chrome switch in behat.yml, but I couldn't get this to work either (the window size didn't change)

My goal: to force all tests to be executed under Chrome with a fixed window size


Solution

  • To do this in @BeforeScenario:

      /**
       * @BeforeScenario
       */
      public function resizeWindow()
      {
        if ($this->getSession()->getDriver() instanceof Selenium2Driver) {
          $this->getMink()->getSession()->start();
          $this->getSession()->resizeWindow(100, 500, 'current');
        }
      }
    

    To do this in @BeforeStep:

      /**
       * @BeforeStep
       */
      public function resizeWindowStep()
      {
        $is_session = $this->getMink()->isSessionStarted();
        if (!$is_session) {
          $this->getMink()->getSession()->start();
        }
        $this->getSession()->resizeWindow(100, 500, 'current');
      }