How to make Behat wait for an AJAX call?

前端 未结 3 773
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 12:15

Scenario: Modify and save an incomplete change to a Campaign

Given I click on the Campaign section folder
And I press Save in the selected Campaign
Then I sh         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 12:48

    I do it by waiting for the DOM to change as a result of the Ajax Call. I made a subclass of DocumentElement, calling it AsyncDocumentElement and overriding the findAll method:

    public function findAll($selector, $locator, $waitms=5000)
    {
        $xpath = $this->getSession()->getSelectorsHandler()->selectorToXpath($selector, $locator);
    
        // add parent xpath before element selector
        if (0 === strpos($xpath, '/')) {
            $xpath = $this->getXpath().$xpath;
        } else {
            $xpath = $this->getXpath().'/'.$xpath;
        }
    
        $page = $this->getSession()->getPage();
    
        // my code to wait until the xpath expression provides an element
        if ($waitms && !($this->getSession()->getDriver() instanceof \Behat\Symfony2Extension\Driver\KernelDriver)) {
            $templ = 'document.evaluate("%s", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null ).snapshotLength > 0;';
    
            $waitJs = sprintf($templ, $xpath);
    
            $this->getSession()->wait($waitms, $waitJs);
        }
    
        return $this->getSession()->getDriver()->find($xpath);
    }
    

    Then in \Behat\Mink\Session I changed the constructor to use that class.

    public function __construct(DriverInterface $driver, SelectorsHandler $selectorsHandler = null)
    {
        $driver->setSession($this);
    
        if (null === $selectorsHandler) {
            $selectorsHandler = new SelectorsHandler();
        }
    
        $this->driver           = $driver;
        $this->page             = new AsyncDocumentElement($this);
        $this->selectorsHandler = $selectorsHandler;
    }
    

    Once I did this, I found my AngularJS tests were working. So far, I've only tested in Firefox.

提交回复
热议问题