JavaScript - Cheat Sheet

From Craft of Testing - Wiki
Jump to navigation Jump to search

What can we help you find?

Language Syntax
XPath Examples

Random
Home Testing Automation AI IoT OS RF Data Development References Tools Wisdom Inspiration Investing History Fun POC Help

Tools

Chrome Snippets

Functions

// JavaScript - Function - Loop - Conditionals
// URL: N/A

var inGlobalContext = true;

function printLessThanFive(){
    var isInLessThanFiveFunction = true;
    console.log('the number is less than 5');  
}

function printIsFive(){
    var isInGreaterThanFiveFunction = true;
    console.log('the number is five');
}

function printGreaterThanFive(){
    var isInGreaterThanFiveFunction = true;
    console.log('the number is greater than five');
}


function runLoop(){
    var inRunLoop = true;
    for (var i=0; i<10; i++){
        if (i<5){
            printLessThanFive();
        }
        else if (i===5){
            printIsFive();
        }
        else{
            printGreaterThanFive();
        }
    }
}

runLoop();
// JavaScript - Function - Multiple Calls
// URL: N/A

function forth(){
    console.log('yay!');
}

function third(){
    var inThird = true;
    console.log('running "third"');
    forth();
}

function second(){
    console.log('running "second"');
    third();
}

function first(){
    for (var i=0; i<10; i++){
        console.log('printing something 10 times', i);
    }
    console.log('running "first"');
    second();
}

first();

Loops

// JavaScript - Loop - Console Output
// URL: N/A

for (var i=0; i<10;i++){
    console.log('Hello World' + i);
}

XPath

// JavaScript - XPath - Click button (Inline)
// URL: http://the-internet.herokuapp.com/login

document.evaluate('//button[@type=\"submit\"]',document.body,null,9,null).singleNodeValue.click();
// JavaScript - XPath - Click button (Multiline)
// URL: http://the-internet.herokuapp.com/login

var LO_Universal = "//button[@type=\"submit\"]";
document.evaluate(`${LO_Universal}`,document.body,null,9,null).singleNodeValue.click();
// JavaScript - XPath - Click button - Pause Udemy Video (Multiline)
// URL: https://www.udemy.com/course/ios-13-app-development-bootcamp/learn/lecture/18002665?start=105#overview

xPathRes = document.evaluate (`//button[@data-purpose='pause-button']`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
xPathRes.singleNodeValue.click();
// JavaScript - XPath - Click button - Play Udemy Video (Multiline)
// URL: https://www.udemy.com/course/ios-13-app-development-bootcamp/learn/lecture/18002665?start=105#overview

xPathRes = document.evaluate (`//button[@data-purpose='play-button']`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
xPathRes.singleNodeValue.click();
// JavaScript - XPath - Click link (Inline)
// URL: http://the-internet.herokuapp.com/login

myFind = document.evaluate (`//a[@href="http://elementalselenium.com/"]`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); myFind.singleNodeValue.click();
// JavaScript - XPath - Click link (Multiline)
// URL: http://the-internet.herokuapp.com/login

var xPathRes = document.evaluate (`//a[@href="http://elementalselenium.com/"]`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
xPathRes.singleNodeValue.click();
// JavaScript - XPath - Count links (Inline) - Cousole Output
// URL: http://the-internet.herokuapp.com/login

locatorCount = document.evaluate(`count(//a)`, document, null, XPathResult.ANY_TYPE, null);
console.log(`This document contains ${locatorCount.numberValue} links.`);
// JavaScript - XPath - Count paragraphs (Inline) - Cousole Output
// URL: http://the-internet.herokuapp.com/login

paragraphCount = document.evaluate('count(//p)', document, null, XPathResult.ANY_TYPE, null);
console.log(`This document contains ${locatorCount.numberValue} paragraphs.`);

Other Example

// Count the number of XPath Locators

var LO_Universal = "//input[@id=\"notification\"]";
var LO_Universal2 = "//input";

var paragraphCount = document.evaluate( 'count(//input)', document, null, XPathResult.ANY_TYPE, null );
alert( 'This document contains ' + paragraphCount.numberValue + ' paragraph elements' );

var paragraphCount = document.evaluate( `count(${LO_Universal})`, document, null, XPathResult.ANY_TYPE, null );
alert( 'This document contains ' + paragraphCount.numberValue + ' paragraph elements' );

var paragraphCount = document.evaluate( `count(//input[@id=\"notification\"])`, document, null, XPathResult.ANY_TYPE, null );
alert( 'This document contains ' + paragraphCount.numberValue + ' paragraph elements' );
// This JavaScript get the value of a field using two different methods.
// URL = https://testtools.ramseysolutions.net/urlauditor

console.log("===== Get Value using getElementById =======");
var MyElement = document.getElementById("UUID").name;
console.log(`MyElement: ${MyElement}`);

console.log("===== Get Value using XPath =======");
var LO_Universal = "//input[@id=\"UUID\"]";
var MyElement = document.evaluate(`${LO_Universal}`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
console.log(`MyElement: ${MyElement.singleNodeValue.name}`);
// This JavaScript gets the value of a hidden field using XPath.
// URL = https://testtools.ramseysolutions.net/urlauditor

console.log("===== Get Hidden Value using XPath =======");
var LO_Universal = "//input[@name=\"campaign_id\"]";
var MyElement = document.evaluate(`${LO_Universal}`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
console.log(`MyElement: ${MyElement.singleNodeValue.value}`);
// This JavaScript get the value of a hidden field using XPath
// Then is changes the hidden value
// Then it gets the changed hidden value.
//
// URL = https://testtools.ramseysolutions.net/urlauditor
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/XPathResult

// Set universal values
var LO_Universal = "//input[@name=\"test_tags\"]";
var MyElement = document.evaluate(`${LO_Universal}`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

console.log("===== Get Value using XPath =======");
var MyValue1 = MyElement.singleNodeValue.value
console.log(`MyValue: ${MyValue1}`);

console.log("===== Set Value using XPath =======");
MyElement.singleNodeValue.value = "heartbaet"

console.log("===== Get Value using XPath =======");
var MyValue2 = MyElement.singleNodeValue.value
console.log(`MyValue: ${MyValue2}`);

Terminology

  • JXA (JavaScript for Automation)

Language Syntax

What can we help you find?

Language Syntax
XPath Examples

Random
Home Testing Automation AI IoT OS RF Data Development References Tools Wisdom Inspiration Investing History Fun POC Help
Functionality

(edit)

Language
Family Specific Details AppleScript C++ JavaScript Ruby Shell Visual Basic
Documentation Comment -- This is a comment // This is a comment // This is a comment # This is a comment # This is a comment ' This is a comment
Collection Array struct myInfo { int myNum; string myName;};
Collection Structure (aka struct) A way to group several related variables into one place. if a > b
Comparison Greater Than if a > b if a > b If a > b Then
Comparison Less Than if a < b if a < b If a < b Then
Comparison Equal To if a == b
Comparison Not Equal To if a != b if a != b If a <> b Then
Computation Addition a = b + c a = b + c
Computation Division a = b / c a = b / c
Computation Multiplication a = b * c a = b * c
Computation Subtraction a = b - c a = b - c
Conditional Case

switch(expression {case x: // code

break;

case y: // code

break;

default:// code

}

case fruit when 'Apple' result = '1 a day' when 'Pear' result = '1 a week' else result = 'unknown' end Select Case(Fruit) Case "Apple" Result = "1 a day" Case "Pear" Result = "1 a week" Case Else Result = "Unknown" End Select
Conditional If - And - Then If a = 1 and b = 2 Then
Conditional If - Or - Then If a = 1 of b = 1 Then
Conditional If - Then - Else if (time < 18) {  cout << "Good day.";} else {  cout << "Good evening.";} if result == 'pass' puts 'Pass' elsif result == 'fail' #Note how elsif is spelled puts 'Fail' else puts 'Other' end If a = b Then print "a equals b" ElseIf a = c Then print "a equals c" Else print "a does not equal b" End If
Conditional Ternary Short-hand if else statement. result = (time < 18) ? "Good day." : "Good evening."; var_is_greater_than_three = (var > 3 ? true : false)
Date Addition EstHours = DateAdd("d",Days,Today)
Date Difference EstHours = DateDiff("h",FirstDate, SecondDate)
Dialog display dialog "Hello World"

var app = Application.currentApplication();
app.includeStandardAdditions = true;
app.displayAlert("This is a message");

IO Input cin >> x; // Get user input
IO Output cout << "Hello World!"; puts "Hello World" echo "Hello World"
IO Serial Monitor or Terminal Serial.begin(115200);Serial.println("Hello\nWorld");" puts "Hello World"
Load URL open location "https://gregpaskal.com/"
Logical And Returns true if both are true if a = 1 && b = 2
Logical Or Returns true if one or the other are true if a = 1 || b = 2
Logical Not Returns true if results are false if a != 1
Loop Do do {  cout << i;  i++;}while (i < 5); i = 0 Do Print "Hello" i = i + 1 If i = "" Then Exit Do End If Loop until i > 5
Loop For for (int i = 0; i < 5; i++) {  cout << i;} for i in 1..10 puts i end For i = 1 to 10 print i Next
Loop While while (i < 5) {  cout << i;  i++;}
Speak
String Concatanation Joining multiple strings together set theDialogText to "The current date and time is " & (current date) & "." fullName = firstName + lastName; filespec = filepath + filename Result = "Age = " & MyAge
String Interpolation (Not possible in AppleScript) Result = "Hello #{first_name}"
String Length Get the length of a string theLen = txt.length();
String New line Start a new line \n
Type Bool bool myBoolean = true;
Type Double double myLargeNum = 556.9923234;
Type Character Store a single character char myLetter = 'D';
Type Float float myFloatNum = 5.99;
Type Integer int myNum = 15; a = Int(12.34)
Type String string myText = "Hello";
Time Delay Waiting for a designated delay delay(250); sleep(1)
Variable Class Shared by all instances of a class @@URL = 'www.mysite.com'
Variable Constant Value to stay the same for the duration of the code execution. Changing value will generate warning. const float PI = 3.14; URL = 'www.mysite.com'
Variable Global Shared across the entire program $URL = 'www.mysite.com'
Variable Instance Belongs to the object itself @URL = 'www.mysite.com'
Variable Local Only accessible from the block it's initialize from set myName to "Bob Smith" a = 1 ma_name="Bob Smith" a = 1
Variable Pre-defined __FILE__ (Current File) __dir__ (Current Directory) __LINE__ (Current Line) MyFile = __FILE__

Reference