Powered By Blogger

Search Here!

Wednesday, April 2, 2014

Get random string, email string and number in Protractor JS !

Get random string, email string and number in Protractor JS.

/**
* Usage: Return Random Email Id.
*/
exports.getRandomEmail = function () {
    var strValues = "abcdefghijk123456789";
    var strEmail = "";
    for (var i = 0; i < strValues.length; i++) {
        strEmail = strEmail + strValues.charAt(Math.round(strValues.length * Math.random()));
    }
    return strEmail + "@mymail.test";
};

/**
* Usage: Generate random string.
* characterLength :  Length of string.
* Returns : Random string.
*/
exports.getRandomString = function (characterLength) {
    var randomText = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < characterLength; i++)
        randomText += possible.charAt(Math.floor(Math.random() * possible.length));
    return randomText;
};

/**
* Usage: Generate random number.
* characterLength :  Length of number.
* Returns : Random number.
*/
exports.getRandomNumber = function (numberLength) {
    var randomNumber = "";
    var possible = "0123456789";
    for (var i = 0; i < numberLength; i++)
        randomNumber += possible.charAt(Math.floor(Math.random() * possible.length));
    return randomNumber;
};

Select Dropdown Value in Protractor JS !

Select value from drop down in Protractor JS using Index, Text and Random Text.

/**
* Usage: selectDropdownByNumber ( element, index)
* element : select element
* index : index in the dropdown, 1 base.
*/
exports.selectDropdownByNumber = function (element, index, milliseconds) {
    element.findElements(by.tagName('option'))
        .then(function (options) {
            options[index].click();
        });
    if (typeof milliseconds != 'undefined') {
        browser.sleep(milliseconds);
    }
};


/**
* Usage: selectDropdownByText (selector, item)
* selector : select element
* item : option(s) in the dropdown.
*/
exports.selectDropdownByText = function selectOption(element, item, milliseconds) {
    var desiredOption;
    element.findElements(by.tagName('option'))
    .then(function findMatchingOption(options) {
        options.some(function (option) {
            option.getText().then(function doesOptionMatch(text) {
                if (text.indexOf(item) != -1) {
                    desiredOption = option;
                    return true;
                }
            });
        });
    })
    .then(function clickOption() {
        if (desiredOption) {
            desiredOption.click();
        }
    });
    if (typeof milliseconds != 'undefined') {
        browser.sleep(milliseconds);
    }
};

/**
* Usage: selectRandomDropdownReturnText ( element, milliseconds)
* element : select random element
* index : wait time to select value for drop down.
*/
exports.selectRandomDropdownReturnText = function (element, milliseconds) {
    return element.findElements(by.tagName('option')).then(function (options) {
        var randomNumber = Math.floor((Math.random() * options.length
        ));
        options[randomNumber].click();
        return options[randomNumber].getText().then(function (text) {
            return text;
        })
    })
    if (typeof milliseconds != 'undefined') {
        browser.sleep(milliseconds);
    }
};

WebDriver Wait Commands !

Wait commands in WebDriver

Listing out the different WebDriver Wait statements that can be useful for an effective scripting and can avoid using the Thread.sleep() comamnds
After few searches and digging into the WebDriver Java doc, I managed to design a mindmap of the different WebDriver commands available



WebDriver.manage().timeouts()

implicitlyWait

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement =
driver.findElement(By.id("myDynamicElement"));


The Implicit Wait will tell the webDriver to poll the DOM for certain duration when trying to find the element, this will be useful when certain elements on the webpage will not be available immediately and needs some time to load.
By default it will take the value to 0, for the life of the WebDriver object instance throughout the test script.

pageLoadTimeout

driver.manage().timeouts().pageLoadTimeout(100, SECONDS);

Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

setScriptTimeout


driver.manage().timeouts().setScriptTimeout(100, SECONDS);

Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.
Support.ui
FluentWait
   // Waiting 30 seconds for an element to be present on the page, checking
   // for its presence once every 5 seconds.
   Wait wait = new FluentWait(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

   WebElement foo = wait.until(new Function() {
     public WebElement apply(WebDriver driver) {
       return driver.findElement(By.id("foo"));
     }
   });


Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.

ExpectedConditions
 
WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(>someid>)));

Models a condition that might reasonably be expected to eventually evaluate to something that is neither null nor false.
Examples : Would include determining if a web page has loaded or that an element is visible.
Note that it is expected that ExpectedConditions are idempotent. They will be called in a loop by the WebDriverWait and any modification of the state of the application under test may have unexpected side-effects.
WebDriverWait will be used as we used in the Expected conditions code snippet as above.
Sleeper is something same as the Thread.sleep() method, but this with an Abstraction around the thread.sleep() for better testability.

AngularJS Wait for element to come into view !

Wait for element in protrator JS.

helper.js

/**
* Usage: wait(element, label)
* element : It will wait for this element to come into view
* label : just used for the error message
*/
exports.wait = function (element, label) {
    browser.wait(function () {
        return element.isPresent().then(function (state) {
            if (state == true) {
                return element.isDisplayed().then(function (state2) {
                    return state2 == true;
                });
            } else {
                return false;
            }
        });
    }, 10000, label + " did not appear");
    browser.sleep(250);
};


Call This Function

Test.js

this.bookContextMenuIcon = $('.context-info-icon');

helper.wait(this.bookContextMenuIcon, "book context menu icon");

AngularJS available Testing Frameworks and Tooling !

Recently I’m discovering a whole new world. The client side world. So looking for all available frameworks and tools I kept in mind it should be working with Visual Studio but it should also stay close to how the inventors of AngularJS did meant it. I made a list of tools and frameworks that are out now and are very helpful.

 Tools and Frameworks
Jasmine: Behavior driven JavaScript testing framework. Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. Runs in Chutzpah. Protractor tests on the AngularJS documentation site are made in Jasmine.
Mocha: JavaScript testing framework. Mocha is a feature-rich JavaScript test framework running on NodeJS and the browser. Runs also in Chutzpah and it’s also possible to write protractor tests with it.
QUnit: QUnit is a JavaScript unit testing framework. It’s used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code. Runs also in Chutzpah.
SinonJS: Standalone test spies, stubs and mocks for JavaScript. No dependencies, works with any unit testing framework.
Chai: Assertion library. Chai is a BDD / TDD assertion library for node and the browser that can be paired with any JavaScript testing framework.
BlanketJS: An easy to install, easy to configure, and easy to use JavaScript code coverage library that works both in-browser and with NodeJS.
PhantomJS: A headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
Chutzpah: JavaScript runner as a Visual Studio extension. Uses PanthomJS as headless browser to run the tests.
NodeJS: Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. NodeJS uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
Karma: JavaScript Test runner build by the AngularJS team formally known as Testangular. Support unittests and e2e tests. Needs NodeJS to run.
Angular scenario Framework: Since Angular v1.2. On their site they advise to use Protractor. If you are starting a new project, we recommend using Protractor for e2e testing AngularJS projects.
Protractor: Protractor is an end to end test framework for AngularJS applications. It’s built on top of WebDriverJS. Protractor runs tests against your application running in a real browser, interacting with it as a user would. You can use together with Jasmine. To run it’s tests it uses selenium. It will replace the Angular scenario Framework.

Conclusion
For now my choice will be a combination of the Jasmine framework for unit testing and Protractor for e2e testing. Jasmine is easy to use and there’s a lot of documentation on the internet. For e2e testing I’ll work with protractor. Integration with Visual Studio is also available but this stays close to how the AngularJS team meant it.