Skip to content

Instantly share code, notes, and snippets.

@fabiang
Created October 2, 2015 15:03
Show Gist options
  • Save fabiang/345ca0444f19b97e370c to your computer and use it in GitHub Desktop.
Save fabiang/345ca0444f19b97e370c to your computer and use it in GitHub Desktop.
Mink + PhantomJS catch JavaScript Errors
<?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();');
}
}
(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));
@spolischook
Copy link

This save my day. Thanx a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment