Created
October 2, 2015 15:03
-
-
Save fabiang/345ca0444f19b97e370c to your computer and use it in GitHub Desktop.
Mink + PhantomJS catch JavaScript Errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Behat\MinkExtension\Context\MinkContext; | |
use Behat\Behat\Context\Context; | |
use Behat\Behat\Context\SnippetAcceptingContext; | |
use Behat\Gherkin\Node\PyStringNode; | |
use Behat\Gherkin\Node\TableNode; | |
/** | |
* Defines application features from the specific context. | |
*/ | |
class BrowserContext extends MinkContext implements Context, SnippetAcceptingContext | |
{ | |
/** | |
* Initializes context. | |
* | |
* Every scenario gets its own context instance. | |
* You can also pass arbitrary arguments to the | |
* context constructor through behat.yml. | |
*/ | |
public function __construct() | |
{ | |
} | |
/** | |
* @AfterStep | |
* @javascript | |
*/ | |
public function checkJsErrors() | |
{ | |
$errors = $this->getSession()->evaluateScript('return ErrorHandler.get();'); | |
if (is_array($errors) && count($errors) > 0) { | |
$lastError = array_pop($errors); | |
throw new \RuntimeException(sprintf( | |
'JS error on page "%s". Message "%s", Filename "%s", Line %s', | |
$this->getSession()->getCurrentUrl(), | |
$lastError['message'], | |
$lastError['filename'], | |
$lastError['lineno'] | |
)); | |
} | |
} | |
/** | |
* @AfterScenario | |
* @javascript | |
*/ | |
public function clearJsErrors() | |
{ | |
$this->getSession()->executeScript('ErrorHandler.clear();'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($, w, stor) { | |
var E = { | |
storageKey: "error_handler", | |
init: function () { | |
$(w).on("error", E.handle); | |
}, | |
handle: function (e) { | |
if (typeof e.originalEvent !== "undefined") { | |
var o = e.originalEvent; | |
var error = { | |
message: o.message, | |
filename: o.filename, | |
lineno: o.lineno, | |
}; | |
var errors = []; | |
if (null !== stor.getItem(E.storageKey)) { | |
errors = JSON.parse(stor.getItem(E.storageKey)); | |
} | |
errors.push(error); | |
stor.setItem(E.storageKey, JSON.stringify(errors)); | |
} | |
}, | |
get: function () { | |
if (null !== stor.getItem(E.storageKey)) { | |
return JSON.parse(stor.getItem(E.storageKey)); | |
} | |
return []; | |
}, | |
clear: function () { | |
stor.setItem(E.storageKey, "[]"); | |
} | |
}; | |
w.ErrorHandler = E; | |
E.init(); | |
}(jQuery, window, localStorage)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This save my day. Thanx a lot!