Selenium - JavaScript

Eyes Object

Eyes object is the main object in Applitools Eyes SDK.


Creation

var Eyes = require('eyes.selenium');
var eyes = new Eyes();

API Key

Before anything else, you should set the API key which allows you work with the Eyes server. Note that you use a static function for that, so it will be available to all of your objects. In order to obtain your API Key, login to Applitools Eyes web application and open your account details page.

eyes.setApiKey("MY_API_KEY");

Replace MY_API_KEY with the API key of your account (you can find it in your signup Email).


Initialization

The open method returns a custom web driver object that monitors all the driver actions. From this point, the new custom driver object should be used for all the actions in the test.

For Ruby users, the initialization and the section for ending a test can be replaced with a call to eyes.test with the same parameters as eyes.open which handles initialization and ending the test.

eyes.open(driver, app_name, test_name, viewport_size);

driver – the relevant Selenium Webdriver object.

appName – string that represents the logical name of the AUT (this name will be presented in the test result)

testName – string that represents the name of the test (this name will be presented in the test result

viewportSize – a predefined viewport size that will be used for the browser window during this test (this parameter is very important for visual tests to ensure that the test will run of a defined viewport size and the results will be consistent)

appWindow (only relevant for CodedUI) – the WinWindow or BrowserWindow object (when using BrowserWindow, a casting to WinWindow is required) of the application under test.


Match Timeout

matchTimeout defines the default amount of time (in milliseconds) that Eyes will wait for an image to stabilize to a point that it is similar to the baseline image (the default value is 2 seconds).

eyes.setDefaultMatchTimeout(TimeOut);

Visual validation checkpoint

The check window command will take a snapshot of the current window in the AUT and will perform smart visual comparison of that window with the baseline. In case this is a new window that does not exist in the baseline, this window will be added to the baseline.

eyes.checkWindow(windowName, matchTimeout);

windowName – string that represents the logical name of this window/validation point that will appear in the test result report.

matchTimeout - (optional) matchTimeout in milliseconds, given for the step to pass.

Visual validation checkpoint of a specific element

The checkElementBy method works in a similar way to check window, except for the fact that it validates the content of an element specified as its input (by means of a WebDriver "By" selector). You can search for an element by its ID, Xpath or CSS selector. If the element's content is overflowing it's visible size, this command will scroll inside the element and stitch the content into a single image (similar to a full page screenshot).


eyes.checkElementBy(By.id("ID"), null, "tag");
tag – a string that represents the logical name of this validation point that will appear in the test result report.

null - using the default match timeout (otherwise, can be an integer value specifying timeout in milliseconds). 


Visual validation checkpoint of a specific region

Check region method works in a similar way to check window, except for the fact that it takes a screenshot of the HTML element specified as its input (by means of a WebDriver "By" selector) instead of a screenshot of the entire web page. The check region command will take a snapshot of the specific object, regardless of where it appears in the page, and will perform smart visual comparison of that region with the baseline. In case this is a new region that does not exist in the baseline, this region will be added as a new region to the baseline.

eyes.checkRegionBy(selector, "window_name", matchTimeout);


selector – the “By” selector (for Selenium Webdriver) that identifies the object region. 

how - the type of the selector that will be passed in ‘what’ field. Could be one of the following: 
:class, :class_name, :css, :id, :link, :link_text, :name, :partial_link_text, :tag_name, :xpath 

what - the selection string suitable to how.

windowName – string that represents the logical name of this window/validation point that will appear in the test result report.

matchTimeout - (optional) matchTimeout in milliseconds, given for the step to pass.


Visual validation checkpoint of iFrames in page


Visually validate a frame:

Iframes are usually scrollable and not displayed fully on the page, it is possible to focus validation only on a specified iFrame so the SDK will scroll and stitch all the parts of the frame into a single picture and thus only one validation step.

eyes.checkFrame(frameElement, null, "tag");

frameElement - the WebElement of the frame.


Visually validate a region inside a frame:

The checkRegionInFrame method enables you to take a screenshot of a region that is located inside a frame in your web page.


eyes.checkRegionInFrame("Frame_Name", By.id("ID"), null, "tag", true);

true - used to specify that this is a scrollable region.

Ending a test

At the end of each test, make sure to call the eyes.close method to notify the service that the test completed successfully. It is recommended to also call the method eyes.abortIfNotClosed at the end of the test as part of the ‘finally’ block to distinguish between completed tests and tests which were aborted abnormally (e.g. an exception was thrown).

    ...
    eyes.close(); 
}finally {
    eyes.abortIfNotClosed();
}

In the “finally” block of Selenium tests, you would usually also want to include “driver.quit()”, since the test has either finished or failed.

 


(Optional) Ending tests without throwing exception on failure


The default behaviour on failure is to throw exception or raise error on test ending. To override this behaviour use the following overrides which takes a boolean.

    ...
    eyes.close(false).then(function(testResults) {
        ...
     });
} finally {
    eyes.AbortIfNotClosed();
}

testResults - Test results details, contains attributes about the test and the failure, such as:

URL - String containing the URL to the report of the test in Applitools dashboard.

Steps - Total steps count

Matches - Total matches count

Mismatches - Total mismatches count

Missing - How many missing steps found

ExactMatches - Amount of matches compared in exact match level

StrictMatches - Amount of matches compared in strict match level

ContentMatches - Amount of matches compared in content match level

LayoutMatches - Amount of matches compared in layour match level

isNew - Boolean value indicates whether the test classified as a new test.


(Optional) Creating a batch of tests

The object BatchInfo represent a batch/collection of tests that will be unified as one group in the Test Manager screen and the result of all tests in a batch will determine the batch result. In order to start a batch, you should create a BatchInfo object, and associate it to the Eyes object (before calling the “eyes.open”). In order to add additional tests to the same batch, make sure to call eyes.setBatch for each of the tests/Eyes objects (so every test in the batch should start with creating an Eyes object, calling eyes.setBatch, eyes.open and ending the test with eyes.close).

eyes.setBatch(batchName, id, startDate);


batchName – string that represents the logical name that will be assigned to this batch.

Use the command eyes.setBatch to associate a test to the batch using the eyes instance

id - (nullable) Unique id to distinguish between the batches.

startDate - (nullable) Starting date string.


(Optional) Enabling Logs


Enabling Logs to Console:

The logHandler method of the Eyes object enables logging for troubleshooting purposes.


var ConsoleLogHandler = require('eyes.selenium').ConsoleLogHandler;
eyes.setLogHandler(new ConsoleLogHandler(true));

Enabling Logs to File:


var FileLogHandler = Eyes_selenium.FileLogHandler;
eyes.setLogHandler(new FileLogHandler(true));

(Optional) Overriding test comparison level

Comparison sensitivity, aka ‘match level’ is set by default to Strict to get optimal coverage. Sometimes for specific tests it is required to change the default comparison level

eyes.setMatchLevel('<Level>');


Level - The match level of the test:
  • Exact - Pixel to pixel comparison, for demonstration purposes and debugging, will fail a test if a pixel is not in place. (not lace. (not recommended)
  • Strict - strict is the default match level, it mimics human eyes so only significant visual changes will be spotted, while small changes that are not visible to a human eye will be ignored.
  • Content - ignores style and anti-aliasing differences, while spotting content changes. (the content level can be useful if your website includes different styles which are not relevant for your tests).
  • Layout - ignores content changes, and detects only layout changes. (useful for pages with dynamic content and localized pages)

Note: Overriding the match level is only effective if set before initialization.



(Optional) Automatic baseline creation (Default: True)

New tests presented to the server are automatically saved as baseline. To override this functionality so baseline creation will be applied manually by reviewing and approving the steps in applitools eyes Test Manager, set ‘SaveNewTests’ to false before test stat.

eyes.setSaveNewTests(true/false);


*true/false - Either true or false.


(Optional) Auto-save on failure (Default: False)

For maintenance and debugging purposes it is possible to make eyes to save automatically failed results as baseline by setting ‘SaveFailedTests’ property to true before test started.

* It is highly unrecommended to set this property in production since all failures will be saved automatically without distinguishment between bugs and features.

eyes.setSaveNewTests(true/false);


*true/false - Either true or false.


(Optional) Force full page screenshot

By default when calling ‘CheckWindow’ on Chrome and Safari, only the visible area (viewport) will be taken as screenshot (this is the default behavior of ChromeDrive and SafariDriver) while with Firefox and IE a full image of the entire page will be captured.

It is possible to set eyes to ‘stitch’ all the scrollable areas into a single screenshot in order to ensure that the result will be similar to IE and Firefox. To set full page stitching pass true to ‘ForceFullPageScreenshot’:

eyes.setForceFullPageScreenshot(true);

Another way of taking fullpage screenshot is using Css transition. Css scrolling and stitching is an alternative way of page scrolling usually comes to help with floating elements to stay in place when scrolling.

eyes.setStitchMode(Eyes.StitchMode.CSS);


(Optional) Setting app environment attributes 


Normally applitools eyes SDKs automatically identifies the environment that is used to run the tests and creates a separate baseline for each environment. In order to override app environment parameters and ‘force’ Eyes to compare results of different environments, you can explicitly call ‘setAppEnvironment’:

hostOs - The OS name and its version or any other os-alike identifier. hostApp - The application name, if there is, such as browser name or any other app-alike identifier.

This functionality can be used to ‘force’ eyes to preset the hostOS and hostApplication so identical tests on different environments will be unified under the same baseline. Note that using this in such way will most likely cause the tests to fail, since in most cases there are some differences between how the AUT is presented in the different environments.

Setting proxy server

This section will explain how to configure a proxy server in the Applitools Eyes SDK to address issues such as connection refused or connection timeout when using Applitools Eyes behind a proxy server. 

  1. npm install tunnel-agent
  2. add 'applitools-http-proxy.js' to your project :

    var tunnel = require('tunnel-agent');
    var https = require('https');
    var __request = https.request;
    var proxy = {     host: '',     port: 0 };
    https.request = function (options, callback) {    
    if (options.host.indexOf('applitools') > -1) {
            var tunnelingAgent = tunnel.httpsOverHttp({
                proxy: {
                    host: proxy.host,
                    port: proxy.port
                   }
              });
            options.agent = tunnelingAgent;
          }
          return __request(options, callback);
     };
     module.exports = function (host, port) {
        proxy.host = host;
        proxy.port = port;
    };


  3. In your app in the beginning insert the line: 
    require('./applitools-http-proxy.js')("proxy_ip", port);

    A full example

    var webdriver = require('selenium-webdriver');
    var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();
    require('./applitools-http-proxy.js')("84.42.3.33", 3128);
    var Eyes = require('eyes.selenium').Eyes;
    var eyes = new Eyes();
    eyes.setApiKey(APPLITOOLS_APIKEY);
    try {
        eyes.open(driver, 'Applitools', 'Test Web Page', {width: 800, height: 600}).then(function (driver) {
            driver.get('http://www.applitools.com');
            // Visual validation point #1
            eyes.checkWindow('Test Web Page');
            driver.findElement(webdriver.By.css('.read_more')).click();
            // Visual validation point #2
            eyes.checkWindow('Features Page');
            eyes.close();
        });
    } finally {
        eyes.abortIfNotClosed();
    }
    driver.quit();