How to make Behat wait for an AJAX call?

user806474 picture user806474 · Sep 25, 2012 · Viewed 12.8k times · Source

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 should see an error balloon informing the changes cannot be saved

Point is that this 'error balloon' in the final step is a ajax call which will then bring a green or red balloon according to the success of the operation. Currently what I do is after 'And I press Save...' I will do a sleep(3) to give it time for this balloon to show up. This doesn't seem very smart coz you are wasting time and also because some times it can take more or less time for this call to be processed.

How do you guys make your behat tests wait for Ajax do be done instead of just putting the beasts to sleep?

thank you very much for any feedback!

Answer

Clarence picture Clarence · Sep 25, 2012

This is done by waiting for your outstanding ajax calls to hit 0. jQuery.active will check just that for you.

In your FeatureContext.php, you can do something like;

public function iShouldSeeAnErrorBalloon($title)
{
    $time = 5000; // time should be in milliseconds
    $this->getSession()->wait($time, '(0 === jQuery.active)');
    // asserts below
}

And do make sure you use a Mink Driver that runs javascript and ajax (the default does not).