Error de captura de JavaScript en Selenium


¿Hay alguna forma de capturar los errores que ocurren en DOM en Selenium y probablemente marcar lo mismo que un error en la página?

Para dar un breve ejemplo, digamos que estoy tratando de enlazar un evento en un control HTML no existente, mi navegador arroja un error que dice:

element abcd not found in the console.

Ahora, si quiero que el mismo error no mis pruebas de selenium y el mensaje que se muestra en el navegador se muestra como el mensaje de error.

Es posible hacer algo como ¿esto?

Author: Alex.K., 2010-11-16

11 answers

Ponga este script en su página y luego compruebe en Selenium para el JsError:

<script type="text/javascript">
    window.onerror=function(msg){
        $("body").attr("JSError",msg);
    }
</script>
 46
Author: jhanifen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-14 16:04:46

Estoy haciendo esto para capturar errores de JavaScript:

[TestCleanup]
public void TestCleanup()
{
    var errorStrings = new List<string> 
    { 
        "SyntaxError", 
        "EvalError", 
        "ReferenceError", 
        "RangeError", 
        "TypeError", 
        "URIError" 
    };

    var jsErrors = Driver.Manage().Logs.GetLog(LogType.Browser).Where(x => errorStrings.Any(e => x.Message.Contains(e)));

    if (jsErrors.Any())
    {
        Assert.Fail("JavaScript error(s):" + Environment.NewLine + jsErrors.Aggregate("", (s, entry) => s + entry.Message + Environment.NewLine));
    }
}
 39
Author: magnusarinell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-22 12:04:39

No estoy seguro cuando esto cambió, pero ahora mismo esto funciona para mí en Python. El archivo es una página simple con un error de javascript.

In [11]: driver.get("file:///tmp/a.html")

In [12]: driver.get_log("browser")
Out[12]: 
[{u'level': u'SEVERE',
  u'message': u'ReferenceError: foo is not defined',
  u'timestamp': 1450769357488,
  u'type': u''},
 {u'level': u'INFO',
  u'message': u'The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.',
  u'timestamp': 1450769357498,
  u'type': u''}]

Python-Selenium versión 2.48.0 Linux Firefox 43.0

 15
Author: kleptog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 07:36:13

JSErrorCollector hace el trabajo.

Una vez configurado, se trata de:

List<JavaScriptError> jsErrorList = JavaScriptError.readErrors(driver);
 5
Author: Leor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-07 17:59:15

Aquí está la solución python webdriver que uso:

def check_browser_errors(driver):
    """
    Checks browser for errors, returns a list of errors
    :param driver:
    :return:
    """
    try:
        browserlogs = driver.get_log('browser')
    except (ValueError, WebDriverException) as e:
        # Some browsers does not support getting logs
        LOGGER.debug("Could not get browser logs for driver %s due to exception: %s",
                     driver, e)
        return []

    errors = []
    for entry in browserlogs:
        if entry['level'] == 'SEVERE':
            errors.append(entry)
    return errors
 5
Author: d3ming,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-14 19:20:37

Solución no basada en window.onerror (no lo intenté): http://sejq.blogspot.com/2008/12/can-selenium-detect-if-page-has.html

 3
Author: Tgr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-11 15:08:44

Me gustaría repetir la respuesta de jhanifen. Aquí hay una solución javascript que no depende de jQuery. Crea una lista HTML invisible en la parte inferior de la página, que contiene los errores.

(function () {
    var ul = null;
    function createErrorList() {
        ul = document.createElement('ul');
        ul.setAttribute('id', 'js_error_list');
        ul.style.display = 'none';
        document.body.appendChild(ul);
    }
    window.onerror = function(msg){
        if (ul === null)
            createErrorList();
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(msg));
        ul.appendChild(li);
    };
})();
 3
Author: Gábor Angyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-25 19:04:23

Solución con "ventana.onerror" no funcionó para mí.

Así que me gustaría señalar otra solución con la alteración de las extensiones de usuario.js que me ayudó:
¿Puede Selenium detectar si la página tiene errores de JavaScript?

Ventaja principal: No es necesario que cambie la fuente de página para hacer la comprobación.

Y aquí está cómo usar las extensiones de usuario.js:
Uso de Extensiones De Usuario Con Selenium-IDE

Nota: Esta solución solo funciona con Firefox

 2
Author: sumid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-17 21:01:23

Aquí mi solución inspiradora por la respuesta de jhanifen:

// common.js - js file common to the entire app
globalError = []
window.onerror = function (msg, url, line, col, error) {
    globalError.push({msg:msg, url:url, line:line})
};

# tests.py
def tearDown(driver):
    # assert on js error 
    ret = driver.selenium.execute_script("return globalError ")
    driver.assertFalse(ret, "errors %r " % ret)
    # ret will be a dict looking like 
    # {'line': 50, 'url': 'http://localhost:8081/static/js/common.js', 'msg': 'Uncaught ReferenceError: s is not defined'}
 2
Author: Ali SAID OMAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-12 09:49:41

Si estás usando java, eres bienvenido a probar esta biblioteca cometida por mí que permite recopilar fácilmente los errores JS recibidos en la sesión de Chromedriver, utilizando anotaciones en los métodos de prueba. Funciona en JUnit5 con anotación extendida, y en TestNG con un oyente analizando la anotación. La anotación contiene valores booleanos que le permiten decidir si desea afirmar o registrar los errores encontrados después de la ejecución de la prueba.

JUnit5 ejemplo:

@Test
@JSErrorsCollectorJUnit
void referenceErrorTest(TestInfo testInfo) throws InterruptedException {

    // Create a new instance of ChromeDriver.
    driver = new ChromeDriver();

    // Set your test name to point its ChromeDriver session in HashMap.
    JSErrorsDriverHolder.setDriverForTest(testInfo.getDisplayName(), driver);

    // Navigate to URL.
    driver.get("http://testjs.site88.net");

    // The click on the button in the test site should cause JS reference error.
    driver.findElement(By.name("testClickButton")).click();
    waitBeforeClosingBrowser();
}
 1
Author: AutomatedOwl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-28 10:04:39

Intenta incluir windows.evento onerror en su página o habilite el cuadro de diálogo mostrar error en opciones de IE. Si elige el último en Se1 se colgará. PS: Esto se ha discutido aquí. Haz una búsqueda.

 0
Author: Rajasankar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-16 04:38:39