Skip to content

Instantly share code, notes, and snippets.

@sbimochan
Last active September 19, 2024 10:36
Show Gist options
  • Save sbimochan/cae10243c5ed304b3d500470ab817ea5 to your computer and use it in GitHub Desktop.
Save sbimochan/cae10243c5ed304b3d500470ab817ea5 to your computer and use it in GitHub Desktop.
Javascript for QA Automation

Javascript for QA Automation

1. An Introduction to JavaScript

JavaScript is an interpreted, powerful, versatile and beginner-friendly programming language that can add interactivity to a website, create servers, create games, etc.

This happens in games, in the behavior of responses when buttons are pressed or with data entry on forms; with dynamic styling; with animation, etc.

2. Fundamentals

2.1 Data Types and Variables

2.1.1 Primitive (Built-in) Data Types

let name = "Ram"            // string
let number = 100            // number
let temperature = 10.6      // number
let isRaining = true        // boolean
let x = null                // null
let y                       // undefined
let symbol = Symbol("RED")  // symbol

2.1.2 Non-Primitive (Derived) Data Types

let person = {                             // object
  name: "John Doe",
  age: 25,
  isStudent: true
};

let colors = ["red", "green", "blue"];     // array

2.2 Variables

var name = "John" // not block scope
var name = "Ram" // Redeclared
name = "Sita"

let age = 10 // block scope
age = 20 // can be updated but not re declared

const birthyear = 1994 // block scope, cannot be redeclared or updated

Best Practices Use const for variables that shouldn't change. Use let for variables that will change. Avoid using var in modern JavaScript due to its function-scoped behavior.

2.3 Operators

Operators are categorized into unary, binary, and ternary based on the number of operands on which they operate in an expression.

2.4 Control Statements

2.4.1 Decision Making Statements

  1. if, if...else, if...else if...else
  2. switch
  3. <statement0> ? <statement1> : <statement2>

2.4.2 Loop

  1. for (the number of iterations is known)
  2. while (as long as a condition is true)
  3. do...while (at least once and then continues if a condition is true)

2.4.3 Jump

  1. continue (starts a new iteration ~)
  2. break (terminates the closest iteration ~)
  3. return (return statement terminates execution ~)

NOTE: ~ is relative scope

2.5 Functions

A function is a block of code designed to perform a particular task.

  1. arrow
  2. normal
2.5.1 Function Parameters and Arguments
  1. Function parameters are the names listed in the function definition.
  2. Function arguments are the real values passed to (and received by) the function.
2.5.2 Higher Order Functions

A function that accepts functions as parameters and/or returns a function.

2.6 Array and Objects

2.6.1 Arrays

const fruits = ["Apple", "Orange", 101, 102]

fruits[0] // "Apple"
fruits[2] // 101
fruits[100] // undefined

Here's how you can categorize these JavaScript array methods based on their importance and usefulness for QA when writing automation tests:

Importance (Commonly Used in Automation Testing):

  • length: Useful for asserting the size of arrays.
  • includes: Important for checking if an array contains a specific element.
  • forEach: Useful for iterating over elements in an array during tests.
  • some: Important for checking if at least one element in the array satisfies a condition.
  • every: Important for verifying that all elements in an array meet a specific condition.
  • map: Useful for transforming data in arrays during test preparation. Returns new array
  • filter: Crucial for creating subsets of data that meet certain conditions.
  • sort: Important for verifying that arrays are ordered as expected.

Useful (Occasionally Used):

  • pop: Used when testing the removal of the last element in an array.
  • shift: Useful for tests that involve removing the first element of an array.
  • push: Used to test appending elements to an array.
  • unshift: Useful for tests that involve adding elements to the beginning of an array.
  • slice: Useful for creating shallow copies of parts of arrays for specific tests.
  • splice: Important for testing modifications of arrays by adding/removing elements.
  • reverse: Occasionally used to verify that an array is in reverse order.
  • concat: Used when tests involve merging arrays.

Not Typically Critical (but can be useful):

  • reverse: Rarely a focus in testing unless testing order specifically.
  • reduce: Not as commonly required but useful for specific aggregations.

2.6.2 Objects

const employee = {
    name: "John Doe",
    id: 528,
    projects: ["Vyaguta", "Trayt"],
    team: [
        { name: "Jane Doe" },
        { name: "Jenny Doe" }
    ],
    getTeamMembers: function(){
        return [this.team[0].name, this.team[1].name]
    }
}

employee.name
employee.projects
employee.team[0].name
employee.getTeamMembers()
  1. Object.keys
  2. Object.values
  3. Object.entries

2.6.3 The rest Operator

const [first, second, third, ...rest] = [1, 2, 3, 4, 5]

const { name, ...attrs } = { name: 'John Doe', id: 528, projects: ["Vyaguta", "Trayt"]}

2.6.4 The spread Operator

const evens = [2, 4]
const odds =  [1, 3, 5]
const numbers = [0, ...evens, ...odds]

const name = "John Doe"
const attrs = { id: 528, projects: ["Vyaguta", "Trayt"] }
const employee = { name: name, ...attrs }

2.7 DOM (Document Object Model)

The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

https://codu-code.github.io/dom-visualizer/index.html https://www.w3schools.com/xml/xml_rss.asp

2.7.1 XML

<breakfast_menu>
  <food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    <calories>650</calories>
  </food>
  <food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>Light Belgian waffles covered with strawberries and whipped cream</description>
    <calories>900</calories>
  </food>
</breakfast_menu>

2.7.2 JSON

{
  "breakfast_menu": {
    "food": [
      {
        "name": "Belgian Waffles",
        "price": "$5.95",
        "description": "Two of our famous Belgian Waffles with plenty of real maple syrup",
        "calories": 650
      },
      {
        "name": "Strawberry Belgian Waffles",
        "price": "$7.95",
        "description": "Light Belgian waffles covered with strawberries and whipped cream",
        "calories": 900
      }
    ]
  }
}

2.7.3 DOM Access

  1. document
  2. getElementsByTagName
  3. getElementById
  4. getElementsByClassName
  5. querySelector
  6. querySelectorAll

2.7.4 DOM Manipulation

// https://www.daraz.com.np/

const images = document.getElementsByTagName("img")
for(const image of images){
    image.setAttribute("src", "https://static1.howtogeekimages.com/wordpress/wp-content/uploads/2020/02/about-blank-url-viewed-in-google-chrome.jpg")
}
  1. getAttribute
  2. setAttribute
  3. innerText
  4. style
  5. classList

2.7.5 Creating Elements

const image = document.createElement("img")

image.setAttribute("src", "https://static1.howtogeekimages.com/wordpress/wp-content/uploads/2020/02/about-blank-url-viewed-in-google-chrome.jpg")

image.style.width = "256px"
image.style.height = "256px"

document.body.append(image)

2.7.6 Event Handlers

https://www.w3schools.com/jsref/dom_obj_event.asp https://www.krishnatraining.com/post.php?pid=2961&id=2&pt=182&gp=0

  1. onclick="handleClick()"
<html>

<head>
  <title></title>
  <script>
    function handleClick(event) {
      console.log(event)
    }
  </script>
</head>

<body>
  <button onclick="handleClick(event)">Click Me</button>
</body>

</html>
  1. button.onclick=()=>{}
<html>

<head>
  <title></title>
</head>

<body>
  <button>Click Me</button>

  <script>
    const button = document.querySelector("button")

    button.onclick = (event) => {
      console.log(event)
    }
  </script>
</body>

</html>
  1. addEventListener, removeEventListener
<html>

<head>
  <title></title>
</head>

<body>
  <button>Click Me</button>

  <script>
    const button = document.querySelector("button")

    const onClickHander = (event) => {
      console.log(event)
    }

    button.addEventListener("click", onClickHander)

    setTimeout(() => {
      button.removeEventListener("click", onClickHander)
    }, 3000)
  </script>
</body>

</html>

2.7.5 Window object

Window is the global object in web browsers.

Even document can be accessed via window.document.querySelector()

Some global variables and methods are:

window.open() //opens a new tab
window.close() //closes the tab
window.alert('Boom!') //Shows a native popup
window.location.href

3 Debugging and Testing

3.1 Logging

image

console.debug(...)
console.info(...)
console.log(...)
console.warn(...)
console.error(...)
console.time(...)

Example

console.table([
    { A: 0, B: 0, OUTPUT: 0 },
    { A: 1, B: 0, OUTPUT: 0 },
    { A: 0, B: 1, OUTPUT: 0 },
    { A: 1, B: 1, OUTPUT: 1 }
])

3.2 Inspecting variables and expressions / Using breakpoints and stepping through code

image

image

  1. Continue
  2. Step Over
  3. Step Into
  4. Step Out

4 Advance JavaScript

4.1 Error handling (try...catch)

try {
    // something that can cause error
} catch(error) {
    // Oops, we have an error from something we tried
}
try {
    // something that can cause error
} catch(error) {
    // Oops, we have an error from something we tried
} finally {
    // Let's clean up our mess
}

4.2 Modules exports and loading

4.2.1 ES5 (require, module)

// anotherscript.js
module.exports = something

// script.js
const m = require('./anotherscript.js')

4.2.2 ES6 (import/export)

// anotherscript.mjs
export something

// script.mjs
import something from './anotherscript.mjs'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment