0% found this document useful (0 votes)
2 views16 pages

JavaScript For Playwright Automation

JavaScript for Playwright automation testing, it has end to end explaination with examples. best for QA Professionals.

Uploaded by

siddeshbasanna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

JavaScript For Playwright Automation

JavaScript for Playwright automation testing, it has end to end explaination with examples. best for QA Professionals.

Uploaded by

siddeshbasanna
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript for Playwright Automation

Naming Conventions
In JavaScript, the most widely accepted naming convention is to use camelCase for variables and functions,
PascalCase for classes and constructors, and UPPER_CASE for constants. Following these conventions
improves readability, consistency, and teamwork.
1. Variables and Functions: Start with a lowercase letter, capitalize each subsequent word.
Example:
let userName = "Singer";
function calculateTotal() { ... }
Rules:
 Must start with a letter, _, or $.
 Avoid reserved keywords (class, return, etc.).
 Use descriptive names (e.g., invoiceAmount instead of x).

2. Classes and Constructors: Each word starts with a capital letter.


Example: for class,
class AccountManager { ... }
function UserProfile(name, age) { ... }
Constants

 UPPER_CASE with underscores: Used for values that never change.


Example:
const MAX_USERS = 100; const API_BASE_URL = "[Link]

4. Boolean Variables: Prefix with is, has, or can for clarity.

Example:
let isActive = true; let hasPermission = false; let canEdit = true;

5. Private Variables (Common in OOP/Frameworks): Prefix with an underscore _ (not enforced by


JavaScript, but widely used).
Example:
class User { constructor(name) { this._password = "secret"; } }

📋 Quick Comparison Table


Type Convention Example
Variables camelCase totalAmount
Functions camelCase getUserData()
Classes PascalCase InvoiceManager
Constructors PascalCase UserProfile()
Constants UPPER_CASE MAX_LIMIT
Booleans is/has/can isLoggedIn, hasAccess
Private Variables _prefix _internalValue
Reserved Keywords lower_case var,const,if,else,new, etc…

⚠️Common Pitfalls to Avoid


 Single-letter names: Avoid x, y, z unless in loops.
 Hungarian notation (prefixing types like strName, intCount) is outdated in JavaScript.
 Inconsistent casing: Mixing camelCase and snake_case leads to confusion.
 Global variables: Use const or let inside scopes to avoid polluting the global namespace.
JavaScript Variables
Variables are "containers" for storing information. JavaScript variables are used to hold values or
expressions.
Rules to declaring a variable
 Name should start with an alphabet (a to z or A to Z), underscore( _ ), or dollar($ ) sign.
 After first character we can use digits (0 to 9).
 variables are case sensitive. for example,a and A are different variables.
 space is not allowed, means name should be single word.
 special chars (symbols) are not allowed in name, except _ and $.
 keywords we can't use as a name.

// var – function-scoped, can be redeclared


Ex: var name = "Tejas";
// let – block-scoped, can be updated but not redeclared in the same scope
Ex: let age = 25;
// const – block-scoped, cannot be updated or redeclared
Ex: const country = "India";
Var Let Const
We use in function or global scope We can in function scope We can in function scope
Block scope not supported Block scope supports Block scope supports
Re assigning value Re assigning value Not supports re assigning
Re declaration of variable supported Not supports Not supports
Since JS1 Since JS6 Since JS6
It supports Hoisting Not supports Not Supports

Types of Variable in JavaScript


 Local Variable
 Outer/Global Variable
Local Variable
A variable which is declared inside block or function is called local variable. It is accessible within the
function or block only.
For example:
Function abc() {
var x=10; //local variable
}
Ex2:
If (10<13) {
var y=20;//javascript local variable
}
Global Variable
variables are declared outside the function & block those are global variables. these global
variables are accessible from anywhere in program.
 declared with window object is known as global variable.
For example:
var value=10; //global variable
function a() {
alert(value);
}
function b() {
alert(value);
}

Declaring global variable through window object


The best way to declare global variable in javascript is through the window object.
Syntax
[Link]=value;
Now it can be declared inside any function and can be accessed from any function.

For example:
function m() {
[Link]=200; //declaring global variable by window object
}
function n() {
alert([Link]); //accessing global variable from other function
}

 Declaration of variables,
The following two ways.
1. Implicit declaration
2. Explicit declaration

Implicit declaration: In every scripting it is the default declaration.


Ex: y=100;

Explicit declaration: All programming languages default declaration


Ex: int a=5;

Scripts are able to support implicit declaration but languages are only explicit declaration.
Note: Explicit declaration is always recommended as a good programming practice.

Data Types & Structures: Arrays, objects, maps, sets


values are generally categorized as either primitive or non-primitive (also known as reference types).
Primitive values include:
Primitive data types: These allow to store data directly. These allow us to store only 1 value @time.
These are popularly known as n n-reference
Javascript has a five primitive data types.

 Strings: It represents textual data, or a series of letters and numbers enclosed in quotation marks. it
should be within a single or double quote.
var name="nit";
var name='nit';
 Number: Represents numeric values, those can be processed and calculated. we don't enclose them
in quotation marks. The numbers can be either positive or negative.
var x1=34.00; with decimals
var x2=34 without decimals
 Boolean: It is used to represent Boolean value either true or false,
These are as follows.
var x = true //equivalent to true, yes or on
var y = false //equivalent to fals , no or off
 undefined: Represents an initialized variable or absence of value.
var x; //now x is undefined
 Null: It represents the intentional absence of any value.
ex: var x=null; //now x is null

 Difference Between null and undefined


null undefined
Represents an intentional absence of value Represents a variable that has been declared but not
assigned a value
Object (historical quirk in JavaScript) Its own type (undefined)
Used by developers to explicitly indicate "no Default state of uninitialized variables or missing
value" function parameters
let x = null; → x is explicitly set to let y; → y is automatically undefined
"nothing"
null == undefined → true (loose equality) null === undefined → false (strict equality)
Return type is ‘object’ Return type is ‘undefined’

🧩 Code Examples
let a; // a is undefined
let b = null; // b is explicitly set to null

[Link](typeof a); // "undefined"


[Link](typeof b); // "object" (quirk!)

[Link](a == b); // true (loose equality)


[Link](a === b); // false (strict equality)

⚖️When to Use
 Use undefined: when the system itself hasn’t assigned a value yet (default state).

 Use null: when you, as the developer, want to deliberately clear a variable or mark it as "empty."

Non-primitive datatypes: These datatypes allow to store reference(address) of data. These datatypes
allow us to store more than 1 value @time.
These are popularly known as reference or composite data types.
Ex: class, array
Non-primitive values are objects, which includes arrays, functions and custom objects.

 How can detect primitive or non-primitive in JavaScript in the following ways:

1. Using the typeof operator:


 the typeof operator is used to determine the type of a given value or variable. It always returns
a string describing the type.
 Examples:
let x = [1, 2, 3];
[Link](typeof x); // "object"

let y = function() {};


[Link](typeof y); // "function"
 typeof null returns “object” even though it’s a primitive value.

2. Using the Object() constructor:


 This constructor creates a new object wrapper for a value.
 If a value is primitive, it will be equal to its object-wrapped version.
 If a value is non-primitive, it won’t be equal to its object-wrapped version.
// Using the object() constructor:
[Link](num === object(num)); //Output: true (primitive)
[Link](obj === object(obj)); //Output: false (non-primitive)

 Is JavaScript, dynamically typed language


Yes — JavaScript is a dynamically typed language. This means you don’t declare variable types
explicitly; instead, the type is determined at runtime based on the value assigned. A variable can change its
type during execution, which makes JavaScript flexible but also prone to type-related bugs.

Characteristics of Dynamic Typing in JavaScript


 No explicit type declaration
Unlike Java or C++, you don’t specify whether a variable is an int, string, or boolean.
let x = 42; // number
x = "hello"; // string
x = [1, 2, 3]; // array

 Type stored with value, not variable


The variable name itself doesn’t carry a type; the value assigned does.
 Runtime type checking
Types are determined and validated while the program is running, not at compile time.
 Automatic type coercion
JavaScript will attempt to convert types when needed:
let result = 5 + "5"; // "55" (string concatenation)

 Function flexibility
Functions can accept arguments of any type without restriction.
function print(x) { [Link](x); }
print(42); // number
print("hello"); // string
print({ key: "val" }); // object

⚖️Advantages vs. Drawbacks


Advantages Drawbacks
Faster prototyping and scripting Harder to catch type-related bugs
Flexible variable usage Can lead to unexpected behavior due to coercion
Easier for beginners Slower execution compared to statically typed languages
Works well for small scripts Large projects may become error-prone

Operators
Operator is a symbol (special char) and it is used to perform certain operation(task).
 Every operator is a symbol,
 but every symbol is not operator.
 Every operator requires some values, those are called as operands.
Ex:
Catagories:
 Unary operators: it requires one operand
 Binary operators: it requires two operands
• Arithmetic
• Relational
• Logical
• Bitwise
• Assignment
• Concatenation
 Ternary operators: it requires three operands
Unary operators: these operators are used to increment or to decrement a value.
operators are ++ and --
 ++ (increment) ==> it adding 1 to an existing value Ex: a++ or ++a
 -- (decrement) ==> it subtracting 1 from an existing value Ex: a-- or --a

Arithmetic operators: using these operators we can perform the basic math
calculations.
Operators are:
Operator Description example
+ addition j+12
- subtraction j-22
* multiplication j*7
/ division j/3
% modulus j%6
** power x**y

Relational operators: these operators are used to provide comparison between two operands. these
are boolean operators (true/false).
Operators are:> < >= <= == != === !==
Operator Description example
== is equal to j==42
!= is not equal to j!=17
> is greater than j>0
< is less than j<100
>= is greater than or equal j>=23
<= is less than or equal j<=13
=== Strictly equal x===y
!== Strictly unequal x!==y

Logical operators: these operators are used to perform multiple comparisons at a time. these are
Boolean operators (true/false).
Operator Description Example
&& And j==1 && k==2
|| OR j<100 || j>0
! Not !(j==k)

assignment operators: these operators are used to store/assign value to memory block
(var/array/objects...)
Assignment operator is ‘=’
Shorthand/compound operator is a combination of assignment and arithmetic/bitwise.
Operators are: += -= /= *= **= &= |= >>= <<= ...
operator Description example
= store a=10 shorthand:
+= addition & assign a+=10
-= subtract & assign a-=5
*= product & assign a*=20
/= division & assign a/=7
%= modulus & assign a%=6
Concatenation operator: this operator is used to concatenation multiple strings then formed into a
single string. One operand should be string to perform concatenation. Resultant value comes in string
format.
Operator is +

Bitwise operators & | ~ ^ >> <<

& Bitwise AND left to right


^ Bitwise XOR left to right
| Bitwise OR left to right

ternary operator: this operator is used to decision making operation. operator is ?:, this operator
also called as conditional operator.
Syntax: (condition)? statement1:statement2

Control Statement
control statements are used to control(change) execution flow of program based on user input data. types:
> conditional statements (dm)
> loops (iterations)
> un-conditional (branching)

Conditional Statements:
There are three forms of if statement.
 if
 If else
 if else if (ladder if)
If Statement:
if is most basic statement of Decision-making
statements. It tells to program to execute a certain
part of code only if particular condition or test case is
true.

Example
var a=10;
if(a>5)
{
[Link]("value of a is greater than 5");
}

if-else statement:
In general, it can be used to execute one block of statement among two blocks.

Example:
var a=40;
if(a%2==0)
{
[Link]("a is even number");
}
else {
[Link]("a is odd number");
}
Result: a is even number

If...else if statement:
It evaluates the content only if expression is true from several expressions.

Syntax
if(expression1)
{
//content to be evaluated if expression1 is true
}
else if(expression2)
{
//content to be evaluated if expression2 is true
}
else
{
//content to be evaluated if no expression is true
}
Example of if..else if statement
var a=40;
if(a==20)
{
[Link]("a is equal to 20");
}
else if(a==5)
{
[Link]("a is equal to 5");
}
else if(a==30)
{
[Link]("a is equal to 30");
}
else
{
[Link]("a is not equal to 20, 5 or 30");
}

switch statement
> switch is selection statement, but it's not decision making.
> it’s better performance.
Syntax:
switch(var/expr)
{
case value: statements...
break;
case value: statements...
break;
case ...
default: statements...
}

Looping Statement:
Set of instructions given to the interpreter to execute until condition becomes false is called loops. The
basic purpose of loop is to minimize code repetition.
The way of the repetition will be forming a circle that's why repetition statements are called loops.
Some loops are available in JavaScript which are given below.
 while loop (top testing/entry level)
 for loop
 do-while (bottom testing/exit level)

while loop
When we are working with “while loop” always pre-
checking process will be occurred. Pre-checking process
means before evolution of statement block condition part
will be executed. “While loop” will repeat in clock wise
direction or anti-clock wise direction.
Example of while loop
var i=10;
while (i<=13)
{
[Link](i + "<br/>");
i++;
}

do-while loop
In implementation when we need to
repeat the statement block at least 1 then go
for do-while. In do-while loop post
checking of the statement block condition
part will be executed.
Example
var i=11; do{
[Link](i + "<br/>");
i++;
}
while (i<=15);

for Loop
For loop is a simplest loop first we
initialized the value then check condition
and then increment and decrements
occurred.

Steps of for loop

Example:
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}

Unconditional statements
These are used to jump/skip statements execution Types:
 break
 continue
 return
Break
The break command will break the loop and continue executing the code that follows after the loop (if
any).
Example
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
[Link]("The number is " + i);
[Link]("<br />");
}

Continue
The continue command will break the current loop and continue with the next value.

Example

var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
[Link]("The number is " + i);
[Link]("<br />");
}

example on conditional statements


//finding abs value
let n = +prompt("enter int value");
if(n<0) {
n=n*-1;
}
[Link]("N val "+n);

//checking even or odd number


let n = +prompt("enter int value"); if(n
%2===0)
[Link](n+" is Even Number"); else
[Link](n+" is Odd Number");

//finding biggest value of 2numbers


let x = +prompt("enter first number");
let y = +prompt("enter second number");

if(x>y)
[Link]("First number is big"); else
if(y>x)
[Link]("Second number is big"); else
[Link]("No one is big");

Example of switch case


let n = +prompt("enter value b/w 1 to 7");
switch(n)
{
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wensday"); break;
case 4: [Link]("Thrusday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Satday"); break;
case 7: [Link]("Sunday"); break;
default: [Link]("Invalid Day");
}
[Link](i+" ");
i++;

Arrays

==> array is ref variable


==> arra is coll of elements
==> it allows same type of values & different types of values
==> storing [Link] values with a same refname is called array Adv
==> simple coding while working [Link] values
==> data maintain
==> easy transporting data
==> JS arrays are dynamic
==> Heap area

=> we can create an array in two ways, those are 1st


Approch:
by using array literal [ ]
Syn:- refvar = [];

2nd Approch:
by using new keyword
Syn:- refvar = new Array();

Asynchronous Programming
 Promises: Promise is an object that represents the eventual completion (success) or failure of an
asynchronous operation. It acts as a placeholder for a value that will be available in the future, helping
developers handle asynchronous tasks more cleanly than traditional callbacks.
Promises in JavaScript are a modern way to handle asynchronous operations, making your code more
readable, maintainable, and robust compared to traditional callbacks.

🔑 Key Points About Promises


 Definition: A Promise is a proxy for a value not known at creation time. It allows us to attach
handlers for success (resolve) or failure (reject).
 States of a Promise:
o Pending: Initial state, operation not yet completed.
o Fulfilled: Operation completed successfully, value available.
o Rejected: Operation failed, error reason available.
 Purpose: Promises help avoid callback hell (deeply nested callbacks) by providing a cleaner,
chainable syntax.

Example of a Promise
let checkEven = new Promise((resolve, reject) => {
let number = 4;
if (number % 2 === 0) {
resolve("The number is even!");
} else {
reject("The number is odd!");
}
});
checkEven
.then((message) => [Link](message)) // Handles success
.catch((error) => [Link](error)); // Handles failure

 If number = 4, the promise resolves with "The number is even!".


 If number = 5, the promise rejects with "The number is odd!".

Why Promises Are Useful


 Cleaner syntax: Instead of nested callbacks, you chain .then() and .catch().

 Error handling: Centralized error management with .catch().


 Async operations: Perfect for API calls, file reading, timers, or any task that completes later.

Promise Chaining Example


fetch("[Link]
.then(response => [Link]())
.then(data => [Link]("Data received:", data))
.catch(error => [Link]("Error:", error));

 Each .then() processes the result of the previous step.


 Errors at any stage are caught by .catch().

Comparison: Callbacks vs Promises


Feature Callbacks Promises
Readability Nested, harder to follow Chainable, cleaner syntax
Error Handling Must handle in each callback Centralized with .catch()
Flexibility Limited flow control Supports chaining & composition
Use Cases Older async code Modern async tasks (API, fetch)

 What is async/await?
Async/Await in JavaScript allows us to write asynchronous code in a clean, synchronous-like manner,
making it easier to read, understand, and maintain while working with promises.
 async functions always return a Promise.
 await pauses execution until the Promise is resolved or rejected.
 Improves readability compared to .then() and .catch() chaining.
 Makes error handling simpler using try...catch.
 Ideal for managing complex asynchronous flows in a structured way.

🔑 How it Works
1. async keyword
o Declares a function as asynchronous.
o An async function always returns a Promise, even if it return a simple value.

o Makes asynchronous code easier to read and maintain


o Does not block the main execution thread
o Always returns a Promise
o Non-promise return values are auto-wrapped in [Link]()
o Works seamlessly with await for handling promises

async function greet() {


let msg "Hello!";
return msg;
}
greet().then(msg => [Link](msg)); // "Hello!"

2. await keyword
o Can only be used inside an async function.
o Pauses execution of async function until the Promise is resolved or rejected.
o Makes code look synchronous, but it’s still non-blocking.
o making asynchronous code easier to read and manage.
o Used to wait for a Promise to settle.
o Prevents callback and .then() chaining.
o Supports error handling with try...catch.

async function fetchData() {


let response = await fetch("[Link]
let data = await [Link]();
[Link](data);
}

Example: Promise vs Async/Await


Using Promises
fetch("[Link]
.then(response => [Link]())
.then(data => [Link]("Data:", data))
.catch(error => [Link]("Error:", error));

Using Async/Await
async function getData() {
try {
let response = await fetch("[Link]
let data = await [Link]();
[Link]("Data:", data);
} catch (error) {
[Link]("Error:", error);
}
}
getData();

👉 Notice how async/await looks cleaner and easier to follow compared to chained .then() calls.

⚡ Benefits of Async/Await

 Readability: Code looks synchronous, easier to understand.


 Error Handling: Use try...catch instead of .catch().
 Debugging: Stack traces are easier to follow.

🛑 Things to Remember
 await only works inside async functions.

 Multiple awaits run sequentially (can slow things down).


Use [Link]() for parallel execution:

async function loadData() {


let [users, posts] = await [Link]([
fetch("/users").then(res => [Link]()),
fetch("/posts").then(res => [Link]())
]);
[Link](users, posts);
}

✅ In short: async/await makes asynchronous JavaScript code simpler, cleaner, and more
maintainable.

 How Playwright tasks queue and resolve.


 Playwright uses an asynchronous, promise-based task queue. Each API call (like click, fill, goto)
is enqueued, and Playwright ensures it resolves only when the required conditions are met (element
readiness, network stability, etc.). This makes test execution deterministic and reduces flakiness

"Playwright queues each action as a promise and resolves it only when the required conditions are met. This
auto-waiting mechanism ensures deterministic execution, meaning tests are less flaky compared to
Selenium. Within a page, tasks run sequentially, but Playwright supports parallelism across multiple
contexts. If a task fails, the queue halts immediately, making debugging straightforward."

3. Functions & OOP


 Arrow Functions: Concise syntax for callbacks.
 Classes & Objects: Page Object Model (POM) design in Playwright.
 Inheritance & Encapsulation: Structuring reusable test utilities.

4. Error Handling & Logging

 Try/Catch: Handling flaky test failures gracefully.


 Custom Errors: Throwing meaningful exceptions.
 Logging: Using [Link], structured logs for debugging.
5. Modules & Imports

 ES6 Modules: import/export for organizing test suites.


 CommonJS: Legacy require usage in [Link] contexts.

6. DOM & Selectors

 Query Selectors: [Link], CSS/XPath basics.


 Playwright Locators: Understanding [Link](), role-based selectors.
 Dynamic Elements: Handling async rendering and shadow DOM.

7. Testing Utilities

 Assertions: Using expect() with Playwright Test runner.


 Mocking & Stubbing: Intercepting network requests.
 API Testing: Leveraging Playwright’s request context.

8. Advanced Topics

 File Handling: Upload/download automation.


 Environment Variables: Config-driven test execution.
 CI/CD Integration: Running Playwright in pipelines.

📊 Comparison Table: JavaScript Topics vs. Playwright Use


JavaScript Topic Playwright Application
Async/Await Waiting for page loads, handling network delays
Classes & OOP Page Object Model for scalable test design
Error Handling Managing flaky tests, retries, and logging
Modules & Imports Organizing test suites into reusable components
DOM Manipulation Locating and interacting with dynamic elements
Promises Handling multiple parallel browser contexts

You might also like