AI-based testing code samples (JavaScript SDK)

This topic shows code samples for using AI-based testing in OpenText Functional Testing for Developers JavaScript tests:

Create a shopping account and place an order

This example shows how to create an account, log in, place an order, and make sure it is registered:

Copy code
var LFT = require("leanft");
var SDK = LFT.SDK;
var Web = LFT.Web;
var AI = LFT.AI;
var expect = require("leanft/expect");
var verify = require("leanft/verify");
var whenDone = LFT.whenDone;
  

describe("Test", function() {
    jasmine : jasmine.DEFAULT_TIMEOUT_INTERVAL = 100 * 1000;
    //mocha: this.timeout(30 * 1000);

    // For Jasmine, use beforeAll(); for Mocha, use before()
    beforeAll(function(done){
        LFT.init(); 
        whenDone(done);
    });
    
    beforeEach(function(done) {
        LFT.beforeTest();
        whenDone(done);
    });

    it("Create account", function(done) {
        // Open web browser
        Web.Browser.launch(Web.BrowserType.Chrome).then(function (browser) {
            
            // Navigate to website
            browser.navigate("https://advantageonlineshopping.com/");
            browser.sync();
            
            // Open sign in form
            browser.$(AI.AiObject({
                aiClass: AI.AiTypes.profile
            })).click();
            
            // Wait for sign in form to load (necessary if the website UI loads slowly)
            setTimeout(function () {
                
                // Navigate to account creation form
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.text_block,
                    text: "CREATE NEW ACCOUNT"
                })).click();
                browser.sync();

                // Enter account details in account creation form
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "ACCOUNT DETAILS"
                })).sendKeys("TestUsername");
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "Email"
                })).sendKeys("test_email@default.com");
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "Password"
                })).sendSecureKeys("TestPass!2");
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "Confirm password"
                })).sendSecureKeys("TestPass!2");
                
                // Enable scrolling down so AI can find remaining test objects that are not currently visible
                AI.RunSettings.autoScroll.enable({"direction": "down", "maxScrolls": 10});
                
                // Accept terms and finish creating account
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.check_box,
                    text: "agree ti LN"
                })).setState(true);
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.button,
                    text: "REGISTER"
                })).click();
                
                browser.close();
                
                whenDone(done);
            }, 10000);
        });
    });
    
    it("Sign in and order", function(done) {
        // Open web browser
        Web.Browser.launch(Web.BrowserType.Chrome).then(function (browser) {
            
            // Navigate to website
            browser.navigate("https://advantageonlineshopping.com/");
            browser.sync();
            
            // Open sign in form
            browser.$(AI.AiObject({
                aiClass: AI.AiTypes.profile
            })).click();
            
            // Wait for sign in form to load (necessary if the website UI loads slowly)
            setTimeout(function () {
                
                // Enter credentials and sign in
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "Username",
                    locator: {direction: "fromTop", index: 0}
                })).sendKeys("TestUsername");
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "Password"
                })).sendSecureKeys("TestPass!2");
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.button,
                    text: "SIGN IN"
                })).click();
                browser.sync();
                
                // Navigate to product page
                browser.navigate("https://advantageonlineshopping.com/#/product/20");
                browser.sync();
                
                // Add item to cart
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.plus,
                    locator: {direction: "fromTop", index: 0}
                })).click();
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.button,
                    text: "ADD TO CART"
                })).click();

                // Navigate to shopping cart
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.shopping_cart
                })).click();
                browser.sync();

                // Initiate checkout
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.button,
                    text: "CHECKOUT (S1,079.96)",
                    locator: {direction: "fromBottom", index: 0}
                })).click();
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.button,
                    text: "NEXT"
                })).click();

                // Enter details
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "SafePay username"
                })).sendKeys("SafePayUser");
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.input,
                    text: "SafePay password"
                })).sendSecureKeys("SafePayPass2");

                // Enable scrolling down so AI can find remaining test objects that are not currently visible
                AI.RunSettings.autoScroll.enable({"direction": "down", "maxScrolls": 10});
                
                // Finish order
                browser.$(AI.AiObject({
                    aiClass: AI.AiTypes.button,
                    text: "PAY NOW"
                })).click();
                browser.sync();

                // Verify order registered
                LFT.Reporter.startReportingContextWithInfo("Verify property: exists", {contextMode: LFT.Reporter.ReportContextMode.Verification});
                verify(browser.$(AI.AiObject({
                        aiClass: AI.AiTypes.text_block,
                        text: "Thank you for buying with Advantage"
                    })).exists()).toBeTruthy();
                LFT.Reporter.endReportingContext();
                
                browser.close();
                
                whenDone(done);
            }, 10000);
        });
    });
    
    it("AI Run Settings", function(done) {
        // Open web browser
        Web.Browser.launch(Web.BrowserType.Chrome).then(function (browser) {
            
            // Navigate to website
            browser.navigate("https://en.wikipedia.org/wiki/Main_Page");
            browser.sync();
            
            // Jump to link in lower part of page
            var completeListLink = browser.$(Web.Link({
                tagName: "A",
                innerText: "Complete list"
            }));
            completeListLink.highlight();
            
            // Configure autoscroll settings to enable scrolling up
            AI.RunSettings.autoScroll.enable({"direction": "up", "maxScrolls": 10});

            // Configure OCR settings to enable detection for English, German, French, Hebrew and Traditional Chinese
            AI.RunSettings.OCR.set({"languages": ["en,de,fr,he,zht"]});
            
            // Navigate to French Wikipedia section
            browser.$(AI.AiObject({
                aiClass: AI.AiTypes.text_block,
                text: "Français"
            })).click();
            browser.sync();
            
            // Jump to text in lower part of page
            var webElement = browser.$(Web.Element({
                tagName: "DIV",
                innerText: "Wikipédia est hébergée par la Wikimedia Foundation, de même que les projets suivants, coordonnés sur le site Méta-Wiki :"
            }));
            webElement.highlight();

            // Verify text block containing French text exists
            LFT.Reporter.startReportingContextWithInfo("Verify property: exists", {contextMode: LFT.Reporter.ReportContextMode.Verification});
            verify(browser.$(AI.AiObject({
                aiClass: AI.AiTypes.text_block,
                text: "Wikipédia est hébergée par la Wikimedia Foundation, de même que les projets suivants, coordonnés sur le site Méta-Wiki :"
            })).exists()).toBeTruthy();
            LFT.Reporter.endReportingContext();
            
            browser.close();
        });

        whenDone(done);
    });

    afterEach(function(done) {
        LFT.afterTest();
        whenDone(done);
    });

    afterAll(function(done) {
        LFT.cleanup();
        whenDone(done);
    });
});

Retrieve the values of AI objects

This example shows how to retrieve the value of an input field:

Copy code
var LFT = require("leanft");
var AI = LFT.AI;
var Web = LFT.Web;
var Reporter = LFT.Reporter;
var expect = require("leanft/expect");



jasmine.DEFAULT_TIMEOUT_INTERVAL = 200000;



var browserName = "Chrome";
var browser;
var aiInput;


describe("AI Tests", function () {

    beforeAll(function (done) {

        LFT.init();

        LFT.whenDone(done);

    });


    beforeEach(function (done) {

        LFT.beforeTest();
        Reporter.setSnapshotCaptureLevel(Reporter.CaptureLevel.All);
        Web.Browser.launch(Web.BrowserType[browserName]).then(function (launched_browser) {
            browser = launched_browser;
            browser.navigate("https://www.advantageonlineshopping.com/#/register");
            //browser.navigate("https://www.advantageonlineshopping.com/#/category/Speakers/4");
            browser.sync();

            aiInput = browser.$(AI.AiObject({
                aiClass: AI.AiTypes.input,
                locator: {
                    direction: "fromRight",
                    index: 0
                }

            }));

        });

        LFT.whenDone(done);

    });



    fit("INPUT getValue", function (done) {

        //aiInput.click();
        aiInput.sendKeys("Hello world!").then(function () {
            aiInput.getValue().then(function (text) {
                console.log("text: " + text);
                expect(text).toEqual("Hello world!");
            });

        });
        
        LFT.whenDone(done);

    });


    afterEach(function (done) {

        LFT.afterTest();
        if (browser) {
            browser.exists(2).then(function (result) {
                if (result)
                    browser.closeAllTabs();
            });

        }

        LFT.whenDone(done);

    });


    afterAll(function (done) {

        LFT.cleanup();
        LFT.whenDone(done);

    });

});

Register a custom class

This example shows a code snippet that registers a custom class:

Copy code
AI.AiUtil.customClass.register("<custom class name>", "<path to image.png>").then(() =>{

        device.$(AI.AiObject({

          aiClass: "<custom class name>"

        })).click();

To unregister the custom class: AI.AiUtil.customClass.unregister("<custom class name>");

To unregister all custom classes: AI.AiUtil.customClass.unregisterAll();

Enable or disable AI Verify Identification

The example below demonstrates how to enable and disable the Verify Identification feature and how it affects the recognition of AI-based test objects.

Copy code
var LFT = require("leanft");
var Web = LFT.Web;
var AI = LFT.AI;
var browser;
var expect = require("leanft/expect");

// Browser name can be defined using the LFT_Browser env var, default is Chrome.
var browserName = process.env.LFT_BROWSER || "Chrome";

describe("should enable and disable the Verify Identification option", function () {
    jasmine : jasmine.DEFAULT_TIMEOUT_INTERVAL = 100 * 1000;
    //mocha: this.timeout(30 * 10000);

    // For Jasmine, use beforeAll(); for Mocha, use before().
    beforeAll(function (done) {
        LFT.init();
        LFT.whenDone(done);
    });

    beforeEach(function (done) {
        LFT.beforeTest();

        Web.Browser.launch(Web.BrowserType[browserName]).then(function (launched_browser) {
            browser = launched_browser;
        });

        LFT.whenDone(done);
    });

    it("should test with Verify Identification enabled, test passes", function (done) {
        // Enable AI Verify Identification.
        AI.RunSettings.verifyIdentification.setEnabled(true);

        // Navigate to the test web page.
        browser.navigate("https://advantageonlineshopping.com");

        // Describe the profile AI test object.
        let profile = browser.$(AI.AiObject({
            aiClass: AI.AiTypes.profile
        }));
        
        // Perfom a click operation. Because AI Verify Identification is enabled,
        // the click is performed only when the profile icon is visible and detected.
        profile.click();

        // Describe a test object contained in the pop-up window that is 
        // displayed after clicking the profile icon above. Highlight it 
        // to check that the clicked was performed successfully.
        let profilePopupWindowText = browser.$(AI.AiObject({
            aiClass: AI.AiTypes.text_block,
            text: "SIGN IN WITH FACEBOOK"
        }));
        profilePopupWindowText.highlight();

        // The isEnabled() method can be used to check if AI Verify Identification is enabled.
        expect(AI.RunSettings.verifyIdentification.isEnabled()).toEqual(true);
        LFT.whenDone(done);
    });

    it("should test with Verify Identification disabled, test fails", function (done) {
        // Disable AI Verify Identification.
        AI.RunSettings.verifyIdentification.setEnabled(false);

        // Navigate to the test web page.
        browser.navigate("https://advantageonlineshopping.com");

        // Describe the profile AI test object.
        let profile = browser.$(AI.AiObject({
            aiClass: AI.AiTypes.profile
        }));
        
        // Perfom a click operation. Because AI Verify Identification is disabled,
        // the click is performed when the control flow reaches this line, with 
        // the possibility that the page is not fully loaded yet, so the profile test
        // object might not exist yet.
        profile.click();

        // Describe a test object contained in the pop-up window that is 
        // displayed after clicking the profile icon above. Highlight it 
        // to check that the clicked was performed successfully. This 
        // fails because the click action above was not performed.
        let profilePopupWindowText = browser.$(AI.AiObject({
            aiClass: AI.AiTypes.text_block,
            text: "SIGN IN WITH FACEBOOK"
        }));
        profilePopupWindowText.highlight();

        // The isEnabled() method can be used to check if AI Verify Identification is enabled.
        expect(AI.RunSettings.verifyIdentification.isEnabled()).toEqual(false);
        LFT.whenDone(done);
    });

    afterEach(function (done) {
        LFT.afterTest();
        if (browser) {
            browser.close();
        }
        LFT.whenDone(done);
    });

    afterAll(function (done) {
        LFT.cleanup();
        LFT.whenDone(done);
    });
});

Enhance identification text recognition

The examples in this section demonstrate ways you can fine tune the text recognition of an object's identification text to achieve an accurate identification: 

Exact text matching for a web object

This example shows how to identify an object in a web application by its text using exact text matching instead of AI matching.

Copy code
it("should identify by text with exact match method for web", function (done) {
    // Launch a new browser instance and navigate to the relevant web page.
    Web.Browser.launch("Chrome").then(function (browser) {
        browser.navigate("https://advantageonlineshopping.com");
        // Describe the AiObject by passing a TextWithMatchOptions property that includes the exact match method.
        let aiObject = browser.$(AI.AiObject({
            aiClass: AI.AiTypes.text_block,
            text: {
                text: "dvantageDemo",
                matchMethod: "ignoreCase"
                // The match method can be specified either by using AI.MatchMethod values
                // or directly as string: "ai" or "ignoreCase".
            }
        }));

        // Verify that the object was identified successfully.
        expect(aiObject.exists()).toEqual(true);

        LFT.whenDone(done);
    });
});

AI text matching for a mobile object

This example shows how to identify an object in a mobile application by its text using AI text matching.

Copy code
it("should dentify by text with AI match method for mobile", function (done) {
    // Lock device by its name.
    Mobile.Lab.lockDeviceByName("MyDevice").then(function (device) {
        // Describe the AiObject by passing a TextWithMatchOptions property that includes the AI match method.
        let aiObject = device.$(AI.AiObject({
            aiClass: AI.AiTypes.text_block,
            text: {
                text: "Gallery",
                matchMethod: AI.MatchMethod.ai
            }
        }));

        // Verify that the object was identified successfully.
        expect(aiObject.exists()).toEqual(true);

        LFT.whenDone(done);
    });
});

Use a regular expression to identify text

This example shows how to identify a text object that varies in the application by using a regular expression.

Copy code
it("should identify by text on web page using a regular expression", function (done) {
    // Launch a new browser instance and navigate to the desired web page.
    Web.Browser.launch("Chrome").then(function (browser) {
        browser.navigate("<amazon shopping cart url>");
        browser.sync();
        
    //Describe the AiObject by passing a TextWithMatchOptions property that uses a regular expression to identify the object's text.
    // The object we want to identify is the shopping cart's title, that looks like this: Subtotal (5 items): $233.57
        let aiObject = browser.$(AI.AiObject({
            aiClass: AI.AiTypes.text_block,
            text: {
                text: /Subtotal \(\d item\): \$[\d.]+/, // or alternatively: new RegExp("Subtotal \(\d item\): \$[\d.]+")
                matchMethod: AI.MatchMethod.ai
            }
        }));

        // Verify that the object was identified successfully.
        expect(aiObject.exists()).toEqual(true);
        
        // Print the text value.
        console.log(aiObject.getValue());

        LFT.whenDone(done);
    });
});

See also