# Setting up and working with the JavaScript SDK

This page covers the basics of installing the JavaScript SDK and structuring your JavaScript test.

In this topic:

## Install the JavaScript SDK as a Node.js module

Before you can use the LeanFT JavaScript SDK that was installed with LeanFT, you must install it as a Node.js module.

1. If a proxy server is used in your organization, you must configure the npm proxy (contact your administrator if needed).

   From a command line, run the following command:

   - For http:

     > npm config set proxy http://<Your Proxy server address or IP>:<Proxy server port>

   - For https:

     > npm config set https-proxy http://<Your Proxy server address or IP>:<Proxy server port>

   For more information, see the npm documentation.

2. Create a folder for your testing project where you will save all your JavaScript tests.

3. If you are working with the Jasmine or Mocha frameworks, use the relevant `npm install` command to install the framework.

   Jasmine | To install, go to https://www.npmjs.com/package/jasmine. After installation, initialize your testing project: In a command line, change to the directory you created for your test project, and run `> jasmine init` to create the spec directory and configuration json.
   Mocha: | To install, go to https://mochajs.org/.

4. Install the LeanFT JavaScript SDK in your testing project folder:

   1. Publish the LeanFT node.js modules to your organization's npm repository by running the following command:

          npm publish <file path to a gzipped tar> --registry=<npm repository address>

      Run this command for each tar file.

      The tar files are located in:

      Windows | <LeanFT installation folder>\SDK\JavaScript\
      Linux/Mac | <LeanFT installation folder>/sdk/JavaScript/

   2. Install the node.js modules for each testing project by running the following command in the project folder:

          npm install leanft --save

   If you are not using an npm repository, you can install the LeanFT JavaScript SDK locally in your testing project folder.

   In your testing project folder, run the following command. Make sure to include the space+period ("`.`") at the end:

   Windows | `<LeanFT installation folder>\SDK\JavaScript\js_installation.bat .`
   Linux/Mac | `<LeanFT installation folder>/sdk/JavaScript/js_installation.sh .`

   Note:

   - We tested this installation script on npm 5. Future changes in npm may affect its functionality.

   - In npm 5 or later, if your testing project folder includes a package.json file, the js_installation script adds all LeanFT JavaScript SDK modules to this file as dependencies with a relative path.

     If you then move your testing project folder or copy it without the node_modules folder, and re-install the dependencies with the `npm install` command, make sure the paths in the package.json are correct. Alternatively, run the js_installation script again in the new location.

Back to top

## Structure your JavaScript test

To create a JavaScript test:

1. Copy the following template.

   Tip: The elements of the template are described in the table below.

   Note:

   - You can write your test in any IDE that supports JavaScript, or in any other text editor.
   - This template uses BDD style.
   - This template can be used both for Jasmine and Mocha. Note the inline comments, however, regarding the difference for each.

       var LFT = require("leanft");
       var SDK = LFT.SDK;
       var Web = LFT.Web;
       var expect = require("leanft/expect");
       var whenDone = LFT.whenDone;

       describe("HP Site",function(){
              // set the default Jasmine time out (if not using Jasmine: remove this line)
       	jasmine : jasmine.DEFAULT_TIMEOUT_INTERVAL = 30 * 1000;

       	// set the default Mocha time out (if not using Mocha: remove this line)
              //mocha: this.timeout(30 * 1000);
              var browser;

       	// For Jasmine, use beforeAll(); for Mocha, use before()
       	beforeAll(function(done){

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

       	beforeEach(function(done){
       		LFT.beforeTest();
       		Web.Browser.launch("chrome").then(function(launchedBrowser){
       			browser = launchedBrowser;
       		})
       		whenDone(done);
       	});

       	it("Should describe the purpose of your test case",function(done){
       		//Navigate to the web site you want to test
       		browser.navigate("http://www.advantageonlineshopping.com:8080");

       		//Add steps here
       		browser.$(Web.Element({
       			id: "TabletsImg"
       		})).click();

       		//gets the list of results
       		var firstProduct = browser.$(Web.Element({
       			tagName: "LI",
       			innerText: /.*HP ElitePad 1000 G2.*/
       		}));

       		//gets the price
       		var priceElement = firstProduct.$(Web.Element({
       			tagName: "a",
       			className: /.*productPrice.*/
       		}));

       		expect(priceElement.innerText()).toEqual("$1,009.00 ");

       		whenDone(done);
       	});

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

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

   Element | Description
   --- | ---
   vars | Variables that define the required LeanFT modules to include and simplified names for the SDK technologies you need to reference. leanft/expect. Provides customized validation functionality. For details, see Validate values below. LFT.whendone. Waits for the LeanFT runtime engine to finish the commands is has received before calling (done). For more details, see JavaScript: Synchronization, promises, and error handling.
   Timeout interval | Must be defined at the head of every test. Jasmine: `jasmine.DEFAULT_TIMEOUT_INTERVAL = 120000;` Mocha: `//this.timeout(20*1000);`
   LFT.init | This step starts the LeanFT runtime engine and enables the creation of the HTML run report. It must run before each test. Use this step to configure the runtime engine address and HTML run report details. For details, see Configure the LeanFT runtime engine and HTML report.
   browser (parent object) setup | The browser variable is defined with global scope at the test fixture level. The Web.Browser.launch step is defined in the beforeEach section, and closed in the afterEach section, so that a clean browser is launched for each test case. If you want to launch browsers with different properties in different test cases, you can launch the browser within the test case. You can also use Web.Browser.attach steps inside your test case to perform steps on new browsers or tabs opened during the test. The launched browser is returned to the launchedbrowser variable when the step's promise is fulfilled. Only then, the browser variable is set. For more details, see JavaScript: Synchronization, promises, and error handling. Note: The template provided on this page is for a Web application. For a mobile application, use the same logic. But instead of launching a browser, use one of the lock device methods available for the LFT.Mobile.MobileLab object.
   it | The test case section. You can have as many test cases as required in your JavaScript file. This section often starts with navigating to your AUT, followed by the required test steps.
   afterEach | Runs after each test case. It closes the browser, clears the SDK initialization, and synchronizes the final done with the LeanFT runtime engine.

2. Save the file:

   Jasmine | Save the file in the spec subfolder under the testing project folder that you created when setting up the JavaScript SDK. Use the following format:
       <myjavascripttest>_spec.js
   Mocha: | In the testing project folder that you created when setting up the JavaScript SDK, create a subfolder called test. Save the file in the test folder.

3. Create test object descriptions. See Describe JavaScript test objects below.

Back to top

## Describe JavaScript test objects

To create LeanFT steps that perform operations on your application, you need to uniquely describe a test object in your application, and you need to specify a LeanFT method or property that is supported for that test object type.

For details on the available test object types and supported operations, see the JavaScript SDK Reference.

Basic syntax

You can use the property bag or builder notation:

    parent.$(TestObjType({
        prop1:value1,
        prop2:value2,
        prop3:value3,
          }
          ));

or

    parent.$(TestObjType().prop1(value1).prop2(value2).prop3(value3))

For example:

    browser.$(Web.Edit({
          type:"text",
          tagName:"INPUT",
          name:"userName"
          }
          ));

or

    browser.$(Web.Edit().type("text").tagName("INPUT").name("userName"))

Short syntax: default WebElement test object

When working with the Web technology, you can omit the test object type. In this case, a WebElement test object is created:

    browser.$({
        innerText = "text"
    });

or

    browser.$(innerText("text"))

Short syntax: CSS selector syntax

If you want to describe a test object by its CSS selector, you can do this by simply providing the CSS string:

    browser.$(".myelementClass");

Regular expressions in descriptions

You can use standard JavaScript regular expression syntax for property values in descriptions.

For example:

    browser.$(Web.Edit().type("text").tagName("INPUT").name(/userN.*/))

Note: Option flags are not supported and will be ignored.

See also: Regular expression guidelines

Specifying complex properties

Some test object identification properties have complex values. For example, grouped properties like location properties with x- and y- values, or dictionary properties, such as the attrs property, that have multiple keys and values.

To create a description for these, follow the examples below:

- grouped property:

      browser.$(Web.Link({
          location: {x: 20, y:30}
      });

  or

      browser.$(Web.Link().location({x:20,y:30});

- dictionary property:

      browser.$(Web.Link({
          attrs: {
              id: "Go"
          }
      });

  or

      browser.$(Web.Link({attrs:{
          id: "Go"
      }});

- Use dot notation to access or update already defined complex properties:

      var desc = Web.Link();
      desc.location().y = desc.location().x + 10;

      desc.attrs().id = "new value"

Using the Object Identification Center (OIC) to generate JavaScript code

You can use the OIC from all of the supported LeanFT IDEs.

Spy objects in your application to view the recommended test object description, optionally fine-tune the properties and values, and then generate the JavaScript code for the test object description in property bag notation.

To generate JavaScript code, open the OIC Settings in your IDE and change the Clipboard Code Language to JavaScript.

For more details on working with the OIC, see Object Identification Center.

See also:

- LeanFT test objects
- Add SDK test object steps to your tests

Back to top

## Find child objects

You can use the `.$$` notation to find all child objects of an object in your application, or all child objects that match a specified filter.

To get all child objects:

    TestObject.$$(null,true).then........

To get all child objects of a specified type:

    TestObject.$$(Technology.Type()).then........

To get all child objects that match the specified filter:

    TestObject.$$(Technology.Type{prop1:value1, prop2:value2}).then........

For example:

    browser.$$(Web.Link{innerText: /.*buy.*/}).then(function(links){
        //do something with the returned links
    })

Back to top

## Validate values

You can use the assert and expect functions supported by your testing framework to validate expected values. This information is included in the run results in the HTML report.

In addition, LeanFT provides customized expect and verify functions.

- The LeanFT expect function differ from Jasmine's in that you can use a catch-then callback to avoid a false expectation from failing the test.

- The LeanFT verify function compares the actual value against the expected value, and returns a Boolean response.

- The LeanFT expect/verify functions support the following matchers, including negative (.not) assertions:

  toBe | toEqual. toNotEqual | toBeNull
  toBeCloseTo(value, NumOfDecimalDigits) | toBeFalsey, toBeFalsy | toBeTruthy
  toContain | toBeGreaterThan, toBeLessThan | toBeUndefined
  toBeDefined | toMatch |

  The syntax for these matchers is the same as the Jasmine syntax.
  For details, see the information about expectations/verfications and matchers at http://jasmine.github.io/2.4/introduction.html

For example:

    it("should provide search results in auto-complete after user types a query",function(done){
    	//Navigate to the web site under test.
    	browser.navigate("http://www.mySite.com");
    	//Open the search widget.
    	browser.$({id: "search_widget"}).click();
    	//Type in the search.
    	browser.$(Web.Edit({name: "abc"})).setValue("xyz");
    	//Verify that the results appear on the screen.var results = browser.$(".js_results");
    	expect(results.exists()).toBeTruthy();
    	verify(results.exists()).toBeTruthy();
    	whenDone(done);
    });

Back to top

## Run your test

1. Manually start the LeanFT runtime engine.

2. In a command line, change to the directory you created for your test project, and run:

   Jasmine | `> jasmine`
   Mocha: | Windows: `> mocha --reporter=.\node_modules\leanft.report\mocha\mochaReporter.js` Linux/Mac: `> mocha --reporter=./node_modules/leanft.report/mocha/mochaReporter.js`

   After the run completes, you can open the generated HTML run report. The report is created in the RunResults folder under your testing project folder. For details on customizing your report, see JavaScript: Configuring the LeanFT runtime engine and HTML report.

Back to top

## JavaScript limitations

The following LeanFT features are not supported when working with the JavaScript SDK:

- Application models
- ALM/BPT integration

Back to top

See also:

- JavaScript: Synchronization, promises, and error handling
- JavaScript: Configuring the LeanFT runtime engine and HTML report

https://admhelp.microfocus.com LeanFT 8942
Tips to improve your search results...TOC Lean Functional Testing Help Center LeanFT Help Center 14.50 - 14.53 All View Local Help Center View Online Help Center back Go back in browser history forward Go forward in browser history Remove search highlights next topic Go to next topic previous topic Go to previous topic Print the current topic Version:(Undefined variable: _rscC_Basic_Variables.FloatingTocShow)