Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to ignore JavaScript exceptions when working with WebDriver (HtmlUnit, Ruby bindings)

HtmlUnit throws exception and crash my test when I'm loading the page

caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true)
driver = Selenium::WebDriver.for(:remote, :desired_capabilities => caps)
driver.navigate.то url

ReferenceError: "x" is not defined. (net.sourceforge.htmlunit.corejs.javascript.EcmaError)

No exception is thrown if I use a Firefox driver.

caps = Selenium::WebDriver::Remote::Capabilities.firefox

Or disable JavaScript for HtmlUnit driver

caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => false)

I am unable to change the code on the test page and fix the problem, so I need to either ignore it or in any way to use Firefox JavaScript Engine instead of the standard HtmlUnit JavaScript Engine.

Is it possible to solve my problem without changing the code of test page?

Update: Tried Capybara + WebKit as an alternative to Selenium + HtmlUnit - works fine, without errors. But still I would like to solve the problem without changing the framework.

like image 581
boxx Avatar asked Jan 05 '12 15:01

boxx


2 Answers

Based on answer from @Vitaly

    import org.openqa.selenium.htmlunit.HtmlUnitDriver;
    import com.gargoylesoftware.htmlunit.WebClient;
    import java.util.logging.Logger;
    import java.util.logging.Level;
    public class MyHtmlUnitDriver extends HtmlUnitDriver {
        protected void modifyWebClient() {
            /* turn off annoying htmlunit warnings */
            Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
            WebClient newWebClient = getWebClient();
            newWebClient.getOptions().setThrowExceptionOnScriptError(false);
            newWebClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            newWebClient.getOptions().setPrintContentOnFailingStatusCode(false);
            modifyWebClient(newWebClient);
        }
    }
like image 121
jechaviz Avatar answered Oct 18 '22 23:10

jechaviz


For Java Only: In the latest version of WebClient (which is wrapped by HTMLUnitDriver) client.setThrowExceptionOnScriptError(false) method is deprecated. In case of subclassing HTMLUnitDriver, you need to override modifyWebClient method:

public class MyHtmlUnitDriver extends HtmlUnitDriver {

...

 @Override
    protected WebClient modifyWebClient(WebClient client) {
        //currently does nothing, but may be changed in future versions
        WebClient modifiedClient = super.modifyWebClient(client);

        modifiedClient.getOptions().setThrowExceptionOnScriptError(false);
        return modifiedClient;
    }
}
like image 28
Vitaliy Grigoruk Avatar answered Oct 18 '22 23:10

Vitaliy Grigoruk