5

I want to execute some javascript on page in @BeforeStep hook that depends on jQuery. However jQuery is not defined at that time, in fact page is blank.

Here's what I am trying to achive:

/**
 * @BeforeStep @javascript
 */
public function registerAjaxEventHandlers()
{
    $javascript = <<<JS
        window.jQuery(document).ready(function () {
            if (window.__ajaxStatus !== undefined) {
                return;
            }
            window.__ajaxStatus = 'none';

            $('body').ajaxStop(function() {
              window.__ajaxStatus = 'idle';
            });

            $('body').ajaxStart(function() {
              window.__ajaxStatus = 'in-flight';
            });
        });
JS;
        //$this->getSession()->wait(5000, 'window.jQuery !== undefined');
        $this->getSession()->executeScript($javascript);
    }

I figured maybe I could wait for the page to load jQuery first (commented line), but it is not true. Seems like execution is halted until that hook is processed.

What is the right place in behat/mink ecosystem to execute javascript on page?

Dziamid
  • 11,225
  • 12
  • 69
  • 104

2 Answers2

5

How about this?

$this->getSession()->wait(5000, 'typeof window.jQuery == "function"');
Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
  • Doesnt help either. Waits for 5 sec while screen is white and continues. – Dziamid Oct 15 '12 at 15:20
  • 1
    I did something similiar, but this causes a scenario to run much longer when a step doesn't interact with the browser, like when loading prerequisite data. Doing a check like `$this->getSession->getCurrentUrl() === 'about:blank'` helps, but perhaps there is a more elegant way. – Adam Elsodaney Sep 14 '15 at 08:49
0

Your javascript is execute before the step, i.e. before the page is loaded. But if you load a page, all kinds of ondomload/pageload JavaScript will be firing already as well.

If you are happy to run it after the initial page, you can use @AfterStep like this:

/**
 * @AfterStep
 */
public function set_selenium_css_selector (Behat\Behat\Event\StepEvent $event) {
  $this->getSession()->wait(10, 'jQuery ("body").addClass ("selenium")');
}
Berend de Boer
  • 100
  • 1
  • 2