├── .gitignore ├── JsPractice ├── ArrowFunction.js ├── arrays.js ├── arraysMethods1.js ├── arraysmethods.js ├── asyncawait.js ├── asyncawaitconcept.js ├── builderpattern.js ├── callback.js ├── callbackhell.js ├── callbackhellVsPromiseChaining.js ├── chain.js ├── classconcept.js ├── coffee.js ├── console.js ├── destructuring.js ├── duplicate.js ├── fetchapi.js ├── fileread.js ├── functions.js ├── ifelse.js ├── inheritance.js ├── loops.js ├── main.js ├── math.js ├── methodoverloading.js ├── methodoverriding.js ├── objectcreate.js ├── pro.js ├── promiseAll.js ├── promiseAllSettled.js ├── promiseAny.js ├── promiseRace.js ├── promiseconcept.js ├── quickTipe.js ├── reverseNumber.js ├── sample.txt ├── staticConcept.js ├── stringmethods.js ├── switchcase.js ├── sync.js ├── templateliterals.js ├── typeOfConcept.js └── variables.js ├── package-lock.json ├── package.json ├── playwright.config.ts ├── tests-examples └── demo-todo-app.spec.ts └── tests └── example.spec.ts /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | /test-results/ 3 | /playwright-report/ 4 | /playwright/.cache/ 5 | -------------------------------------------------------------------------------- /JsPractice/ArrowFunction.js: -------------------------------------------------------------------------------- 1 | const square = num => num * num; 2 | const result = square(5); 3 | console.log(result); 4 | 5 | const mesg = () => 'hello JS'; 6 | console.log(mesg()); 7 | 8 | const add = (a,b) => a+b; 9 | console.log(add(4,5)); 10 | 11 | 12 | const getFullName = (person) => `${person.firstName} ${person.lastName}` 13 | 14 | const person = { 15 | firstName: 'Naveen', 16 | lastName: 'Automation Labs' 17 | } 18 | 19 | const fullName = getFullName(person); 20 | console.log(fullName); 21 | 22 | // 23 | const greet = (username='guest', age=0) => `Hello, ${username}! you are ${age} years old`; 24 | const g1 = greet(); 25 | console.log(g1); 26 | 27 | const g2 = greet('Tom', 30); 28 | console.log(g2); 29 | 30 | //rest parameters ... varargs 31 | const sum = (...numbers) => numbers.reduce((acc, num) => acc+num, 0); 32 | const total = sum(1,2,3,4,5); 33 | console.log(total); 34 | 35 | // 36 | const browserInfo = (browser = 'chrome', ...details) => { 37 | console.log(`Browser: ${browser}`); 38 | console.log('other details:', details); 39 | }; 40 | 41 | browserInfo(); 42 | browserInfo('firefox', '115.11', 'mozilla', 'headless'); 43 | 44 | //max number using Math 45 | const findMaxNumber = (a,b,c) => { 46 | return Math.max(a,b,c); 47 | }; 48 | 49 | const maxValue = findMaxNumber(10,30,50); 50 | console.log(maxValue); 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /JsPractice/arrays.js: -------------------------------------------------------------------------------- 1 | // Declaration of an array 2 | let myArray = []; // An empty array 3 | 4 | 5 | let lang = ["Java", "Python", "JS"]; 6 | //1. push: 7 | lang.push("Ruby", "HTML"); 8 | console.log(lang); 9 | 10 | //2. pop: 11 | let numbers = [1, 2, 3, 4, 5];// An array with numbers 12 | numbers.pop(); 13 | console.log(numbers); 14 | 15 | //3. shift: 16 | let fruits = ["apple", "banana", "orange"]; // An array with strings 17 | let fistFruit = fruits.shift(); 18 | console.log(fistFruit); 19 | console.log(fruits); 20 | 21 | //4. unshift: 22 | let colors = ['red', 'green', 'black', 'white']; //An array containing two elements 23 | console.log(colors.length); 24 | colors.unshift('blue', 'pink'); 25 | console.log(colors); 26 | console.log(colors.length); 27 | 28 | //5. splice: 29 | let animals = ['dog','cat','bird','fish']; // Array contains four string values 30 | animals.splice(1,2,'bear','elephant'); 31 | console.log(animals); 32 | 33 | //6. slice: 34 | let pop = [1,2,3,4,5]; 35 | let newPop = pop.slice(1,4);//(] 36 | console.log(newPop); 37 | 38 | //7. concat: 39 | let fr = ["apple", "banana", "orange"];; 40 | let num = [1,2,3,4]; 41 | let mixedArray = fr.concat(num); 42 | console.log(mixedArray); 43 | 44 | //8. indexOf: 45 | let color = ["black", "red", "green", "blue", "red"]; 46 | let indexRed = color.indexOf("red"); 47 | console.log(indexRed); 48 | let naveenIndex = color.indexOf("naveen"); 49 | console.log(naveenIndex); 50 | 51 | //2nd red index: 52 | let redSecondIndex = color.indexOf("red", color.indexOf("red")+1); 53 | console.log(redSecondIndex); 54 | 55 | //9. includes: 56 | let test = ["admin", "customer", "seller", "vendor"]; 57 | let flag = test.includes("seller", "naveen"); 58 | console.log(flag); 59 | 60 | //10. forEach: 61 | let n = [1,2,3,4,5,6,7]; 62 | n.forEach((e) => { 63 | console.log(e * 2); 64 | }) 65 | -------------------------------------------------------------------------------- /JsPractice/arraysMethods1.js: -------------------------------------------------------------------------------- 1 | //1. every(): 2 | let num = [1,2,3,4,5]; 3 | let flag = num.every((e) => e<10); 4 | console.log(flag); 5 | 6 | //2. some(): 7 | let number = [1,2,3,4,5]; 8 | let fg = number.some((e) => e % 2 === 0); 9 | console.log(fg); 10 | 11 | //3. find(): 12 | let total = [1,2,3,5,7,9]; 13 | let fe = total.find((e) => e%2===0); 14 | console.log(fe); 15 | 16 | //4. indexOf(): 17 | let arry = ['apple', 'banana','mango', 'pear']; 18 | let indexof_str = arry.indexOf('mango'); 19 | //-1 if not found in 20 | console.log("index of mango: ", indexof_str ); 21 | 22 | //5. lastIndexOf(): 23 | let fruits = ['apple', 'apple', 'banana','mango', 'pear' ]; 24 | let lastApple = fruits.lastIndexOf('apple'); 25 | console.log(lastApple); 26 | 27 | //6. reverse(): 28 | let frts = ['apple', 'banana','mango', 'pear' ]; 29 | let revFruits = frts.reverse(); 30 | console.log(revFruits); 31 | 32 | //7. sort(): 33 | let products = ['macbook', 'imac','samsung', 'canon' , '123test', 'Tshirt']; 34 | let proSort = products.sort(); 35 | console.log(proSort); -------------------------------------------------------------------------------- /JsPractice/arraysmethods.js: -------------------------------------------------------------------------------- 1 | //1. map: 2 | let numbers = [1,2,3]; 3 | let doubleNumbers = numbers.map((e) => e * 2); 4 | console.log(doubleNumbers);//[2,4,6] 5 | 6 | // F -> C 7 | //(F-32) * (5/9) 8 | let fahTemp = [32,68,86,104,212]; 9 | 10 | function fahToCel(fah){ 11 | return (fah - 32) * (5/9); 12 | } 13 | 14 | let celTemp = fahTemp.map(fahToCel); 15 | console.log(celTemp); 16 | 17 | //2. filter: 18 | let num = [1,2,3,4,5,6,7,8,9,10]; 19 | let evenNum = num.filter((e) => e % 2 === 0); 20 | console.log(evenNum); 21 | 22 | 23 | let employee = [ 24 | {name:"John", age:30, gender:"male" }, 25 | {name:"Bob", age:35, gender:"male" }, 26 | {name:"Lisa", age:40, gender:"female" }, 27 | {name:"Priya", age:25, gender:"female" }, 28 | {name:"Peter", age:55, gender:"male" }, 29 | ]; 30 | 31 | let femaleEmpOver30 = employee.filter((emp) => { 32 | return emp.gender === "female" && emp.age > 20; 33 | }); 34 | console.log(femaleEmpOver30); 35 | 36 | //3. reduce: 37 | let numb = [1,2,3,4,5]; //15 38 | let sum = numb.reduce((acc,num) => acc+num, 0); 39 | console.log(sum); 40 | //1st --> 0+1 = 1 41 | //2nd --->1+2 = 3 42 | //3rd ---->3+3 = 6 43 | //4th--->6+4=10 44 | //5th--->10+5 = 15 45 | 46 | //max number in the array: 47 | let top = [10,5,25,8,30,15]; //30 48 | let maxNum = top.reduce((max,num) => {//max = 30, num = 8 49 | if(num > max){//8>30 50 | return num;//30 51 | } 52 | else{ 53 | return max;//30 54 | } 55 | }, top[0]); 56 | 57 | console.log(maxNum); 58 | 59 | //cart : name, price 60 | let cartItems = [ 61 | {name:"Jeans", price:500}, 62 | {name:"Shirt", price:300}, 63 | {name:"Shoes", price:1000}, 64 | {name:"Hat", price:100}, 65 | {name:"Tshirt", price:400}, 66 | ]; 67 | 68 | 69 | let totalCost = 70 | cartItems.reduce((total, item) => total + item.price, 0); 71 | console.log(totalCost); 72 | -------------------------------------------------------------------------------- /JsPractice/asyncawait.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/naveenanimation20/JavaScript_FullCourse/515fc8cacdac9a972d8dba1fe94c82def75ef814/JsPractice/asyncawait.js -------------------------------------------------------------------------------- /JsPractice/asyncawaitconcept.js: -------------------------------------------------------------------------------- 1 | //async function without await 2 | 3 | async function f1(){ 4 | console.log("this is async function without await step"); 5 | return 42; //return a promise(resolved) on top of 42 6 | } 7 | 8 | // f1() 9 | // .then(result=>{ 10 | // console.log(result); 11 | // }); 12 | 13 | //async function without await but with error: 14 | async function f2(){ 15 | console.log('this is an async function with error'); 16 | throw new Error("this is my error"); //return a promise(rejected) 17 | } 18 | 19 | // f2().catch(error =>{ 20 | // console.log(`the error message ${error}`); 21 | // }) 22 | 23 | //async function with a resolved/rejecte promise: 24 | function getInfo(){ 25 | return new Promise((resolve, reject)=>{ 26 | const randomNumber = Math.random(); 27 | setTimeout(()=>{ 28 | if(randomNumber < 0.5){ 29 | resolve(randomNumber); 30 | }else{ 31 | reject(new Error("wrong value error")); 32 | } 33 | }, 2000); 34 | }) 35 | } 36 | 37 | //create async function which is calling getinfo() 38 | async function getNumberInfo(){ 39 | try{ 40 | const result = await getInfo(); //async step 41 | console.log("Result: ", result); 42 | } 43 | catch(error){ 44 | console.log("Error:", error); 45 | } 46 | } 47 | 48 | //call getNumberInfo(): 49 | getNumberInfo(); 50 | 51 | async function f3(){ 52 | 53 | await f2(); 54 | } -------------------------------------------------------------------------------- /JsPractice/builderpattern.js: -------------------------------------------------------------------------------- 1 | // Define an object with chainable methods 2 | // const calculator = { 3 | // value: 0, 4 | 5 | // // A method to add a number 6 | // add(x) { 7 | // this.value += x; 8 | // return this; // Return the modified object 9 | // }, 10 | 11 | // // A method to subtract a number 12 | // subtract(x) { 13 | // this.value -= x; 14 | // return this; // Return the modified object 15 | // }, 16 | 17 | // // A method to multiply by a number 18 | // multiply(x) { 19 | // this.value *= x; 20 | // return this; // Return the modified object 21 | // }, 22 | 23 | // // A method to divide by a number 24 | // divide(x) { 25 | // this.value /= x; 26 | // return this; // Return the modified object 27 | // }, 28 | 29 | // // A method to get the current value 30 | // getValue() { 31 | // return this.value; 32 | // } 33 | // }; 34 | 35 | // // Example of method chaining 36 | // const result = calculator 37 | // .add(5) 38 | // .multiply(2) 39 | // .subtract(10) 40 | // .divide(3) 41 | // .getValue(); 42 | 43 | // console.log(result); // Outputs: 0 44 | 45 | 46 | 47 | 48 | const fetchData = async () => { 49 | try { 50 | // Simulate an asynchronous operation, e.g., fetching data from an API 51 | const response = await fetch('https://reqres.in/api/users'); 52 | // Check if the HTTP request was successful 53 | if (!response.ok) { 54 | throw new Error('Failed to fetch data'); 55 | } 56 | // Parse the JSON response 57 | const data = await response.json(); 58 | // Do something with the data 59 | //console.log(data); 60 | return data; 61 | } catch (error) { 62 | // Handle errors that may occur during the async operation 63 | console.error('An error occurred:', error); 64 | } 65 | }; 66 | 67 | // Call the async function 68 | fetchData().then(data=>{ 69 | console.log(data); 70 | }).catch((error)=>{ 71 | console.log("Error", error); 72 | }); 73 | -------------------------------------------------------------------------------- /JsPractice/callback.js: -------------------------------------------------------------------------------- 1 | //callback function 2 | //async call/task -- once this task is completed -- then only callback function will be called 3 | 4 | // //basic callback: 5 | // function greet(name, callback){ 6 | // console.log('Hello' + name);//normal/sync step/task , could be async call/api 7 | // callback(); 8 | // } 9 | 10 | // //callback function 11 | // function welcome(){ 12 | // console.log('welcome!!!!'); 13 | // } 14 | 15 | // greet('Naveen', welcome); 16 | 17 | 18 | 19 | // //callback with async function: 20 | // function printInfo(name, callback){ 21 | // //async function/task/step: 22 | // setTimeout(function(){ 23 | // console.log("printing info for " + name); 24 | // callback("plz call me back..."); 25 | // }, 5000);//delay of 5000ms/5 sec 26 | // } 27 | 28 | // //callback 29 | // function displayMessage(mesg){ 30 | // console.log(mesg); 31 | // } 32 | 33 | // printInfo("Lisa", displayMessage); 34 | 35 | // 36 | function fetchUserData(userId, callback) { 37 | setTimeout(function () { 38 | const users = { 39 | 1: { id: 1, name: "Naveen" }, 40 | 2: { id: 2, name: "Tom"}, 41 | }; 42 | 43 | const user = users[userId]; 44 | if (user) { 45 | callback(null, user); 46 | } else { 47 | callback("User not found", null); 48 | } 49 | }, 5000); // Simulating a delay of 1 second 50 | } 51 | 52 | //callback function: 53 | function handleUserData(error, user){ 54 | if(error){ 55 | console.error("Error :" , error); 56 | }else{ 57 | console.log("User: " , user); 58 | } 59 | } 60 | 61 | fetchUserData(1, handleUserData); -------------------------------------------------------------------------------- /JsPractice/callbackhell.js: -------------------------------------------------------------------------------- 1 | //"pyramid of doom" or "callback hell" 2 | 3 | asyncFunction1((result1) => { 4 | asyncFunction2(result1, (result2) => { 5 | asyncFunction3(result2, (result3) => { 6 | asyncFunction4(result3, (result4) => { 7 | // More nested callbacks... 8 | }); 9 | }); 10 | }); 11 | }); 12 | 13 | 14 | 15 | 16 | //better readability with Promises: 17 | asyncFunction1() 18 | .then(result1 => asyncFunction2(result1)) 19 | .then(result2 => asyncFunction3(result2)) 20 | .then(result3 => asyncFunction4(result3)) 21 | .then(result4 => { 22 | // Code here 23 | }) 24 | .catch(error => { 25 | // Error handling 26 | }); 27 | 28 | 29 | 30 | // or using async-await: 31 | async function myFunction() { 32 | try { 33 | const result1 = await asyncFunction1();//5 34 | const result2 = await asyncFunction2(result1);//10 35 | const result3 = await asyncFunction3(result2); 36 | const result4 = await asyncFunction4(result3); 37 | // Code here 38 | } catch (error) { 39 | // Error handling 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /JsPractice/callbackhellVsPromiseChaining.js: -------------------------------------------------------------------------------- 1 | //Call Back Hell vs Promise Chaining 2 | 3 | // Start the coffee machine. 4 | // Grind coffee beans. 5 | // Boil water. 6 | // Pour boiling water into a cup. 7 | // Add ground coffee to the cup. 8 | // Stir the coffee. 9 | // Enjoy your coffee! 10 | 11 | function startCoffeeMachine() { 12 | return new Promise((resolve) => { 13 | console.log('Starting the coffee machine...'); 14 | setTimeout(() => { 15 | console.log('Coffee machine is ready.'); 16 | resolve('coffee machine is ready'); 17 | }, 2000); 18 | }); 19 | } 20 | 21 | function grindCoffeeBeans() { 22 | return new Promise((resolve) => { 23 | console.log('Grinding coffee beans...'); 24 | setTimeout(() => { 25 | console.log('Coffee beans are ground.'); 26 | resolve('ground coffee'); 27 | }, 1000); 28 | }); 29 | } 30 | 31 | function boilWater() { 32 | return new Promise((resolve) => { 33 | console.log('Boiling water...'); 34 | setTimeout(() => { 35 | console.log('Water is boiled.'); 36 | resolve('boiled water'); 37 | }, 1500); 38 | }); 39 | } 40 | 41 | function pourBoilingWaterIntoCup(boiledWater) { 42 | return new Promise((resolve) => { 43 | console.log('Pouring boiling water into a cup...'); 44 | setTimeout(() => { 45 | console.log('Boiling water is in the cup.'); 46 | resolve(boiledWater + ' in cup'); 47 | }, 500); 48 | }); 49 | } 50 | 51 | function addCoffeeToCup(groundCoffee) { 52 | return new Promise((resolve) => { 53 | console.log('Adding ground coffee to the cup...'); 54 | setTimeout(() => { 55 | console.log('Coffee is added to the cup.'); 56 | resolve('coffee is added to ' + groundCoffee); 57 | }, 500); 58 | }); 59 | } 60 | 61 | function stirCoffee(coffeeInCup) { 62 | return new Promise((resolve) => { 63 | console.log('Stirring the coffee...'); 64 | setTimeout(() => { 65 | console.log('Coffee is stirred.'); 66 | resolve('enjoyable ' + coffeeInCup); 67 | }, 300); 68 | }); 69 | } 70 | 71 | function enjoyCoffee(finalCoffee) { 72 | console.log('Enjoying my ' + finalCoffee); 73 | } 74 | 75 | 76 | //promise chaining: 77 | startCoffeeMachine((coffeeMachineStatus)=>{ 78 | console.log(coffeeMachineStatus); 79 | return grindCoffeeBeans(); 80 | }) 81 | .then((groundCoffee)=>{ 82 | console.log(groundCoffee); 83 | return boilWater(); 84 | }) 85 | .then((boliedWater)=>{ 86 | console.log(boliedWater); 87 | return pourBoilingWaterIntoCup(boliedWater); 88 | }) 89 | .then((waterInCup)=>{ 90 | console.log(waterInCup); 91 | return addCoffeeToCup(waterInCup); 92 | }) 93 | .then((coffeeInCup)=>{ 94 | console.log(coffeeInCup); 95 | return stirCoffee(coffeeInCup); 96 | }) 97 | .then((finalCoffee)=>{ 98 | enjoyCoffee(finalCoffee); 99 | }) 100 | .catch((error)=>{ 101 | console.log("Error occured", error); 102 | }); 103 | 104 | -------------------------------------------------------------------------------- /JsPractice/chain.js: -------------------------------------------------------------------------------- 1 | function getEvenNumber(value, delay){ 2 | 3 | return new Promise((resolve, reject)=>{ 4 | 5 | setTimeout(()=>{ 6 | if(value % 2 == 0){ 7 | resolve(value); 8 | } 9 | else{ 10 | reject(new Error("value is not even number")); 11 | } 12 | }, delay); 13 | }); 14 | } 15 | 16 | //promise chain: 17 | getEvenNumber(4, 1000) 18 | .then(result =>{ 19 | console.log("step 1 : gettng the result with even number: ", result); 20 | return getEvenNumber(7, 2000); 21 | }) 22 | .then(result => { 23 | console.log("step 2 : gettng the result with even number: ", result); 24 | 25 | }) 26 | .catch(error =>{ 27 | console.error("promise chain error: ", error.message); 28 | }); -------------------------------------------------------------------------------- /JsPractice/classconcept.js: -------------------------------------------------------------------------------- 1 | class Car{ 2 | 3 | constructor(name, price, model, color){ 4 | this.name = name; 5 | this.price = price; 6 | this.model = model; 7 | this.color = color; 8 | } 9 | 10 | refuel(){ 11 | console.log(this.name + " car is refueld"); 12 | } 13 | } 14 | 15 | //new keyword: to create the object: 16 | const c3 = new Car("Audi"); 17 | console.log(c3.name); 18 | console.log(c3.price); 19 | console.log(c3.model); 20 | console.log(c3.color); 21 | 22 | const c1 = new Car("BMW", 100, "520d", "Black"); 23 | 24 | console.log(c1.name); 25 | console.log(c1.price); 26 | console.log(c1.model); 27 | console.log(c1.color); 28 | c1.refuel(); 29 | 30 | console.log("---------"); 31 | 32 | const c2 = new Car("Honda", 20, "Civic", "White"); 33 | 34 | console.log(c2.name); 35 | console.log(c2.price); 36 | console.log(c2.model); 37 | console.log(c2.color); 38 | c2.refuel(); 39 | -------------------------------------------------------------------------------- /JsPractice/coffee.js: -------------------------------------------------------------------------------- 1 | // Start the coffee machine. - 2 secs 2 | // Grind coffee beans. - 1 sec 3 | // Boil water. - 1.5 sec 4 | // Pour boiling water into a cup. - 0.5 sec 5 | // Add ground coffee to the cup. - 0.5 sec 6 | // Stir the coffee. - 0.3 sec 7 | // Enjoy your coffee! 8 | 9 | function startCoffeeMachine(callback) { 10 | console.log('Starting the coffee machine...'); 11 | setTimeout(function () { 12 | console.log('Coffee machine is ready.'); 13 | callback('coffee machine is ready'); 14 | }, 2000); 15 | } 16 | 17 | function grindCoffeeBeans(callback) { 18 | console.log('Grinding coffee beans...'); 19 | setTimeout(function () { 20 | console.log('Coffee beans are ground.'); 21 | callback('ground coffee'); 22 | }, 1000); 23 | } 24 | 25 | function boilWater(callback) { 26 | console.log('Boiling water...'); 27 | setTimeout(function () { 28 | console.log('Water is boiled.'); 29 | callback('boiled water'); 30 | }, 1500); 31 | } 32 | 33 | function pourBoilingWaterIntoCup(boiledWater, callback) { 34 | console.log('Pouring boiling water into a cup...'); 35 | setTimeout(function () { 36 | console.log('Boiling water is in the cup.'); 37 | callback(boiledWater + ' in cup'); 38 | }, 500); 39 | } 40 | 41 | function addCoffeeToCup(groundCoffee, callback) { 42 | console.log('Adding ground coffee to the cup...'); 43 | setTimeout(function () { 44 | console.log('Coffee is added to the cup.'); 45 | callback('coffee is added to ' + groundCoffee); 46 | }, 500); 47 | } 48 | 49 | function stirCoffee(coffeeInCup, callback) { 50 | console.log('Stirring the coffee...'); 51 | setTimeout(function () { 52 | console.log('Coffee is stirred.'); 53 | callback('enjoyable ' + coffeeInCup); 54 | }, 300); 55 | } 56 | 57 | function enjoyCoffee(finalCoffee) { 58 | console.log('Enjoying my ' + finalCoffee); 59 | } 60 | 61 | // Start the coffee machine. 62 | // Grind coffee beans. 63 | // Boil water. 64 | // Pour boiling water into a cup. 65 | // Add ground coffee to the cup. 66 | // Stir the coffee. 67 | // Enjoy your coffee! 68 | 69 | 70 | //callback hell: 71 | startCoffeeMachine(function (coffeeMachineStatus){ 72 | grindCoffeeBeans(function (groundCoffee){ 73 | boilWater(function (boiledWater){ 74 | pourBoilingWaterIntoCup(boiledWater, function (waterInCup){ 75 | addCoffeeToCup(groundCoffee, function (coffeeInCup){ 76 | stirCoffee(coffeeInCup, function (finalCoffee){ 77 | enjoyCoffee(finalCoffee); 78 | }) 79 | }) 80 | }) 81 | }) 82 | }) 83 | }) 84 | 85 | //callback hell with arrow =>: 86 | startCoffeeMachine( (coffeeMachineStatus)=>{ 87 | grindCoffeeBeans( (groundCoffee) => { 88 | boilWater( (boiledWater) => { 89 | pourBoilingWaterIntoCup(boiledWater, (waterInCup)=> { 90 | addCoffeeToCup(groundCoffee, (coffeeInCup)=>{ 91 | stirCoffee(coffeeInCup, (finalCoffee)=>{ 92 | enjoyCoffee(finalCoffee); 93 | }) 94 | }) 95 | }) 96 | }) 97 | }) 98 | }) 99 | -------------------------------------------------------------------------------- /JsPractice/console.js: -------------------------------------------------------------------------------- 1 | // console.log("hello world"); 2 | // console.error("array error"); 3 | // console.warn("some warning!!"); 4 | // console.info("this is my js code"); 5 | 6 | const user = { 7 | name: "john", 8 | age: 34, 9 | city: "Bangalore", 10 | contry: "India" 11 | }; 12 | 13 | const user1 = { 14 | name: "Lisa", 15 | age: 30, 16 | city: "LA", 17 | contry: "USA" 18 | }; 19 | console.table({user,user1}); 20 | 21 | // 22 | // console.group("Login feature"); 23 | // console.log("reset pwd"); 24 | // console.log("error login mesg"); 25 | // console.log("enter username/password"); 26 | // console.groupEnd(); 27 | 28 | 29 | // console.time("print 1 to N values"); 30 | // for (let i=1;i<=100000;++i){ 31 | // console.log(i); 32 | // } 33 | // console.timeEnd("print 1 to N values") 34 | 35 | console.log("%c I love JavaScript Coding!!!", 36 | "color:red; background-color:lightblue; border:solid"); 37 | 38 | 39 | -------------------------------------------------------------------------------- /JsPractice/destructuring.js: -------------------------------------------------------------------------------- 1 | //array/object ---> variables 2 | 3 | //array: 4 | const numbers = [1,2,3,4,5]; 5 | const [a,b,c,d] = numbers; 6 | console.log(a); 7 | console.log(b); 8 | console.log(c); 9 | console.log(d); 10 | 11 | const lang = ["JavaScript", "Java", "Ruby", "Python", "GO"]; 12 | const [p,q, ...testLang] = lang; 13 | console.log(p); 14 | console.log(q); 15 | console.log(testLang); 16 | 17 | //Object: 18 | const user = { 19 | firstName: "Tom", 20 | lastName :"Smith", 21 | age: 30 22 | }; 23 | 24 | const {firstName, lastName, city="LA", age} = user; 25 | console.log(firstName); 26 | console.log(lastName); 27 | console.log(age); 28 | console.log(city); 29 | 30 | //function params: 31 | //without destrucring: 32 | // function printUserName(person){ 33 | // console.log( person.firstName + ' ' + person.lastName ); 34 | // } 35 | 36 | // const person = { 37 | // firstName:"John" , 38 | // lastName :'Doe', 39 | // }; 40 | // printUserName(person); 41 | 42 | //with destrucring: 43 | function printUserName({lastName}){ 44 | console.log( lastName ); 45 | } 46 | 47 | const person = { 48 | firstName:"Testing" , 49 | lastName :'Automation', 50 | }; 51 | 52 | printUserName(person); 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /JsPractice/duplicate.js: -------------------------------------------------------------------------------- 1 | const numbers = [1, 2, 3, 4, 4, 4, 4, 5, 6, 6, 7]; 2 | const names = ["Naveen", "Tom", "Lisa", "Naveen", "Peter", "Tom", "Raj", "Robby", "Tom"]; 3 | 4 | const uniqueNumbers = [... new Set(numbers)]; 5 | console.log(uniqueNumbers); 6 | 7 | const uniqueNames = [... new Set(names)]; 8 | console.log(uniqueNames); 9 | 10 | 11 | -------------------------------------------------------------------------------- /JsPractice/fetchapi.js: -------------------------------------------------------------------------------- 1 | const fetchUserInfo = async ()=>{ 2 | try{ 3 | const response = await fetch('https://reqres.in/naveen/users?page=2');//async step 4 | 5 | if(!response.ok){ 6 | throw new Error('user data not found...'); 7 | } 8 | 9 | //parse json response: 10 | const userData = await response.json();//async step: 11 | console.log(userData); 12 | } 13 | catch(error){ 14 | console.log("Error:", error) ; 15 | } 16 | 17 | } 18 | 19 | //call the function: 20 | fetchUserInfo(); -------------------------------------------------------------------------------- /JsPractice/fileread.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs/promises'); // Import the fs.promises module 2 | 3 | // Define a function to read a file and return a Promise 4 | function readFilePromise(filePath) { 5 | return fs.readFile(filePath, 'utf-8'); 6 | } 7 | 8 | // Usage example 9 | const filePath = 'sample1.txt'; // Replace with the path to your file 10 | 11 | readFilePromise(filePath) 12 | .then(content => { 13 | console.log('File content:', content); 14 | }) 15 | .catch(error => { 16 | console.error('Error reading the file:', error); 17 | }); 18 | -------------------------------------------------------------------------------- /JsPractice/functions.js: -------------------------------------------------------------------------------- 1 | //1. function decalration: 2 | 3 | function add(a,b){ 4 | return a+b; 5 | } 6 | 7 | function print(){ 8 | console.log("hi this is JS"); 9 | } 10 | 11 | const sum = add(5,6); 12 | console.log(sum); 13 | 14 | print(); 15 | 16 | //2. Function Expression: Annonymous function 17 | const multiply = function(x, y){ 18 | return x*y; 19 | } 20 | const mul = multiply(5,6); 21 | console.log(mul); 22 | 23 | //3. Arrow function expression:Annonymous function 24 | const divide = (t1,t2) => t1/t2; 25 | const div = divide(20,2); 26 | console.log(div); 27 | 28 | //4. Function Constructor: 29 | const substract = new Function('a', 'b' , 'return a - b;'); 30 | const subs = substract(10,2); 31 | console.log(subs); 32 | 33 | //5. IIFE(Immediately Invoked Function Expression): 34 | (function(){ 35 | console.log("server is up n running on port 3000"); 36 | })(); 37 | 38 | 39 | //6. Generator Function: 40 | //function* and yield keyword 41 | function* generateNumbersSequence(){ 42 | yield 1; 43 | yield 2; 44 | yield 3; 45 | yield 4; 46 | } 47 | 48 | const generator = generateNumbersSequence(); 49 | console.log(generator.next().value); 50 | console.log(generator.next().value); 51 | console.log(generator.next().value); 52 | console.log(generator.next().value); 53 | 54 | //7. Annonymous function: 55 | //no specific name 56 | // const numbers = [1,2,3,4,5]; 57 | // const squareNumbers = numbers.map(function(e){ 58 | // return e * e; 59 | // }); 60 | // console.log(squareNumbers); 61 | 62 | const numbers = [1,2,3,4,5]; 63 | const squareNumbers = numbers.map((e) =>{ 64 | return e * e; 65 | }); 66 | console.log(squareNumbers); 67 | 68 | //8. Recursive function:4 -> 4*3*2*1=24 69 | function factorial(n){ 70 | if(n === 0 || n === 1){ 71 | return 1; 72 | } 73 | else{ 74 | return n * factorial(n-1); 75 | } 76 | } 77 | 78 | console.log(factorial(4)); 79 | console.log(factorial(5)); 80 | console.log(factorial(100)); 81 | 82 | 83 | //9. Higher-Order Function: 84 | function additon(a,b){ 85 | return a+b; 86 | } 87 | 88 | function multiplication(a,b){ 89 | return a*b; 90 | } 91 | 92 | function operate(funcName, a, b){ 93 | return funcName(a,b); 94 | } 95 | 96 | const s = operate(multiplication, 4, 5); 97 | console.log(s); -------------------------------------------------------------------------------- /JsPractice/ifelse.js: -------------------------------------------------------------------------------- 1 | // function checkAge(age){ 2 | // if(age >=18){ 3 | // console.log("You are old enough to vote."); 4 | // } 5 | // else{ 6 | // console.log("Sorry, you must be 18 or older to vote"); 7 | // } 8 | // } 9 | 10 | // checkAge(10); 11 | // checkAge(30); 12 | // checkAge(0); 13 | 14 | // // 15 | // function checkNumber(number){ 16 | // if(number > 0){ 17 | // console.log('number is +ve'); 18 | // } 19 | // else if(number < 0 ){ 20 | // console.log('number is -ve') ; 21 | // } 22 | // else{ 23 | // console.log('zero number found.'); 24 | // } 25 | // } 26 | 27 | // checkNumber(10); 28 | // checkNumber(-9); 29 | // checkNumber(0); 30 | 31 | // //nested if-else: 32 | // function checkGrade(score){ 33 | // let grade; 34 | // if(score >=90){ 35 | // grade = 'A'; 36 | // } 37 | // else{ 38 | // if(score >=80){ 39 | // grade ='B' 40 | // } 41 | // else{ 42 | // if (score>=70) { 43 | // grade='C'; 44 | // } 45 | // else{ 46 | // grade = 'D' 47 | // } 48 | // } 49 | // } 50 | // console.log(grade); 51 | // } 52 | 53 | // checkGrade(90); 54 | // checkGrade(75); 55 | // checkGrade(35); 56 | // checkGrade(100); 57 | // checkGrade(85); 58 | 59 | // 60 | // let browser = "chrome"; 61 | // if( browser == "chrome"){ 62 | // console.log("launch chrome"); 63 | // } 64 | // if( browser == "edge"){ 65 | // console.log("launch edge"); 66 | // } 67 | // if( browser == "firefox"){ 68 | // console.log("launch firefox"); 69 | // } 70 | // else{ 71 | // console.log("plz pass the right browser...."); 72 | // } 73 | 74 | //if -elseif 75 | let browser = "opera"; 76 | if( browser == "chrome"){ 77 | console.log("launch chrome"); 78 | } 79 | else if( browser == "edge"){ 80 | console.log("launch edge"); 81 | } 82 | else if( browser == "firefox"){ 83 | console.log("launch firefox"); 84 | } 85 | else{ 86 | console.log("plz pass the right browser...."); 87 | } 88 | -------------------------------------------------------------------------------- /JsPractice/inheritance.js: -------------------------------------------------------------------------------- 1 | class Automobile{ 2 | constructor(chasisNumber){ 3 | this.chasisNumber = chasisNumber; 4 | } 5 | useAeroDynamic(){ 6 | console.log("Automobile -- aerodynamic " + this.chasisNumber); 7 | } 8 | 9 | } 10 | 11 | //parent (super class) 12 | class Vehicle extends Automobile{ 13 | constructor(make, model, year){ 14 | super(1000); 15 | this.make = make; 16 | this.model= model; 17 | this.year = year; 18 | } 19 | 20 | getInfo(){ 21 | return `${this.make}, ${this.model}, ${this.year}`; 22 | } 23 | startEngine(){ 24 | console.log('Starting engine...' + this.make); 25 | } 26 | stopEngine() { 27 | console.log("Stopping Engine..."); 28 | } 29 | } 30 | 31 | //child(Sub class): 32 | class Car extends Vehicle{ 33 | constructor(make, model, year, fuelType){ 34 | super(make, model, year);//call the parent class constructor 35 | this.fuelType = fuelType; 36 | } 37 | 38 | driverCar(){ 39 | console.log('driving the car ' + this.model + " " + this.fuelType); 40 | } 41 | } 42 | 43 | //child(Sub class): 44 | class Truck extends Vehicle{ 45 | constructor(make, model, year, loadingCapacity){ 46 | super(make, model, year);//call the parent class constructor 47 | this.loadingCapacity = loadingCapacity; 48 | } 49 | 50 | driverTruck(){ 51 | console.log('driving the truck ' + this.model + " capacity " + this.loadingCapacity); 52 | } 53 | } 54 | 55 | //creating the objects (instances): new keyword: 56 | const car = new Car("Honda", "Civic", 2023, "Petrol"); 57 | const truck = new Truck("Tata", "Sumo", 2020, 100); 58 | 59 | car.startEngine(); 60 | console.log(car.getInfo()); 61 | car.driverCar(); 62 | car.useAeroDynamic(); 63 | console.log(car.chasisNumber); 64 | 65 | truck.startEngine(); 66 | console.log(truck.getInfo()); 67 | truck.driverTruck(); 68 | -------------------------------------------------------------------------------- /JsPractice/loops.js: -------------------------------------------------------------------------------- 1 | //for loop: 2 | //1 to 10: 3 | for(let i=0; i<=9; i++){ 4 | console.log(i);//1 2 3 4 ....10 5 | } 6 | 7 | console.log("------"); 8 | 9 | //for...of loop: 10 | const array = [1,2,3,4,5];//0 to 4 => 5 11 | for(const e of array){ 12 | console.log(e); 13 | } 14 | // 15 | console.log("------"); 16 | for( let i=0; i { 3 | // return new Promise((resolve, reject) => { 4 | // setTimeout(() => { 5 | // const userData = { id: 1, name: "John Doe", email: "john@example.com" }; 6 | // resolve(userData); 7 | // }, 1000); 8 | // }); 9 | // }; 10 | 11 | // // fetching user's posts based on user data 12 | // const fetchUserPosts = (userId) => { 13 | // return new Promise((resolve, reject) => { 14 | // setTimeout(() => { 15 | // const userPosts = [ 16 | // { id: 101, title: "Post 1", content: "This is the first post" }, 17 | // { id: 102, title: "Post 2", content: "This is the second post" } 18 | // ]; 19 | // resolve(userPosts); 20 | // }, 1500); 21 | // }); 22 | // }; 23 | 24 | // // Chaining promises to fetch user data and user posts 25 | // fetchUserData() 26 | // .then(user => { 27 | // console.log("User data:", user); 28 | // return fetchUserPosts(user.id); // Return a promise for the next step in the chain 29 | // }) 30 | // .then(posts => { 31 | // console.log("User posts:", posts); 32 | // }) 33 | // .catch(error => { 34 | // console.error("Error:", error); 35 | // }); 36 | 37 | 38 | 39 | 40 | 41 | // const myPromise = new Promise((resolve, reject) =>{ 42 | // setTimeout(() => { 43 | // const t = Math.random(); 44 | // if (t > 0.3){ 45 | // resolve(t); 46 | // } 47 | // else{ 48 | // reject("some error"); 49 | // } 50 | // }, 1000); 51 | // }); 52 | 53 | // myPromise 54 | // .then(result =>{ 55 | // console.log("promise fulfilled " ,result ); 56 | // }) 57 | // .catch(error =>{ 58 | // console.log('promise rejected ' + error ) ; 59 | // }) 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /JsPractice/promiseAll.js: -------------------------------------------------------------------------------- 1 | // case: 1 2 | //f1 -- resolve 3 | //f2 -- resolve 4 | //f3 -- resolve 5 | // const function1 = ()=>{ 6 | // return new Promise((resolve, reject)=>{ 7 | // setTimeout(()=> { 8 | // //resolve("Data from function 1"); 9 | // const data = [1,2,3,4,5]; 10 | // resolve(data); 11 | // }, 2000); 12 | // }); 13 | // }; 14 | 15 | // const function2 = ()=>{ 16 | // return new Promise((resolve, reject)=>{ 17 | // setTimeout(()=> { 18 | // //resolve("Data from function 2"); 19 | // const data = [6,7,8,9]; 20 | // resolve(data); 21 | // }, 2000); 22 | // }); 23 | // }; 24 | 25 | // const function3 = ()=>{ 26 | // return new Promise((resolve, reject)=>{ 27 | // setTimeout(()=> { 28 | // //resolve("Data from function 3"); 29 | // const data = [10,11,12,13]; 30 | // resolve(data); 31 | // }, 2000); 32 | // }); 33 | // }; 34 | 35 | // Promise.all([ 36 | // function1(), 37 | // function2(), 38 | // function3() 39 | // ]) 40 | // .then(dataArray =>{ 41 | // console.log("All data from diff functions: ", dataArray); 42 | // }) 43 | // .catch(error =>{ 44 | // console.log('Error in promise', error); 45 | // }); 46 | 47 | 48 | 49 | //case 2: 50 | //f1 -- resolved 51 | //f2 -- rejected 52 | 53 | const getData = ()=>{ 54 | return new Promise((resolve, reject)=>{ 55 | setTimeout(()=> { 56 | resolve("Data from getData"); 57 | }, 2000); 58 | }); 59 | }; 60 | 61 | const getError = ()=>{ 62 | return new Promise((resolve, reject)=>{ 63 | setTimeout(()=> { 64 | reject("Error: data is not available from getError"); 65 | }, 2000); 66 | }); 67 | }; 68 | 69 | Promise.all([ 70 | getData(), 71 | getError() 72 | ]) 73 | .then(dataArray => { 74 | console.log("All data fetched: " + dataArray); 75 | }) 76 | .catch(error => { 77 | console.log("Error occured: ", error); 78 | }) 79 | -------------------------------------------------------------------------------- /JsPractice/promiseAllSettled.js: -------------------------------------------------------------------------------- 1 | // Promise.allSettled(): 2 | 3 | // Behavior: 4 | //It returns a single promise that is fulfilled with an array of result objects, one for each promise. 5 | // Each result object contains: 6 | // a status (either "fulfilled" or "rejected") and 7 | // a value (fulfilled value) or reason (rejection reason). 8 | 9 | // Use Case: 10 | // Useful when you want to process all promises, whether they succeed or fail, 11 | // and you want to gather information about the outcome of each promise. 12 | 13 | //case: 14 | //f1 -- resolved 15 | //f2 -- rejected 16 | 17 | const getData = ()=>{ 18 | return new Promise((resolve, reject)=>{ 19 | setTimeout(()=> { 20 | resolve("Data from getData"); 21 | }, 2000); 22 | }); 23 | }; 24 | 25 | const getError = ()=>{ 26 | return new Promise((resolve, reject)=>{ 27 | setTimeout(()=> { 28 | reject("Error: data is not available from getError"); 29 | }, 2000); 30 | }); 31 | }; 32 | 33 | Promise.allSettled([ 34 | getData(), 35 | getError() 36 | ]) 37 | .then(results =>{ 38 | results.forEach(result =>{ 39 | if(result.status === 'fulfilled'){ 40 | console.log("value: " , result.value); 41 | } 42 | else{ 43 | console.error("reason for rejection: ", result.reason); 44 | } 45 | }) 46 | }) -------------------------------------------------------------------------------- /JsPractice/promiseAny.js: -------------------------------------------------------------------------------- 1 | // It's used for handling multiple promises and resolving with the value of the first fulfilled/resolved promise, similar to Promise.race(). 2 | // However, unlike Promise.race(), Promise.any() doesn't reject immediately when the first promise rejects; 3 | // instead, it waits until at least one promise fulfills/resolved. 4 | 5 | const getMessage = () => { 6 | return new Promise((resolve, reject) => { 7 | setTimeout(() => { 8 | reject("get Message from API 1"); 9 | }, 500); 10 | }); 11 | }; 12 | 13 | const getUsers = () => { 14 | return new Promise((resolve, reject) => { 15 | setTimeout(() => { 16 | reject("Error: User Data could not be fetched"); 17 | }, 200); 18 | }); 19 | }; 20 | 21 | const getProducts = () => { 22 | return new Promise((resolve, reject) => { 23 | setTimeout(() => { 24 | reject("Error: Product Info could not be fetched"); 25 | }, 1000); 26 | }); 27 | }; 28 | 29 | Promise.any([getMessage(), getUsers(), getProducts()]) 30 | .then(result => { 31 | console.log("First successful result:", result); // Will log the first resolved promise result 32 | }) 33 | .catch(errors => { 34 | console.error("All promises rejected:", errors); // Will log all rejection reasons if all promises reject 35 | }); 36 | -------------------------------------------------------------------------------- /JsPractice/promiseRace.js: -------------------------------------------------------------------------------- 1 | // Function that returns a resolved promise 2 | const resolvePromise = () => { 3 | return new Promise((resolve, reject) => { 4 | setTimeout(() => { 5 | resolve("Resolved!"); 6 | }, 300); 7 | }); 8 | }; 9 | 10 | // Function that returns a rejected promise 11 | const rejectPromise = () => { 12 | return new Promise((resolve, reject) => { 13 | setTimeout(() => { 14 | reject("Rejected!"); 15 | }, 500); 16 | }); 17 | }; 18 | 19 | // Use Promise.race() to see which promise settles first 20 | Promise.race([ 21 | resolvePromise(), 22 | rejectPromise() 23 | ]) 24 | .then(result => { 25 | console.log("Result: ", result); 26 | }) 27 | .catch(error =>{ 28 | console.log("Error ", error); 29 | }) 30 | -------------------------------------------------------------------------------- /JsPractice/promiseconcept.js: -------------------------------------------------------------------------------- 1 | const randomNumberPromise = new Promise((resolve, reject) => { 2 | 3 | //async operation: 4 | setTimeout(()=>{ 5 | const randomValue = Math.random(); 6 | if(randomValue > 0.5){ 7 | resolve(randomValue); 8 | }else{ 9 | reject(new Error("value is too small!")); 10 | } 11 | 12 | }, 2000);//delay of 2 secs 13 | }); 14 | 15 | randomNumberPromise 16 | .then(result => {//handler 17 | console.log("promise is fulfilled with value: " , result); 18 | }) 19 | .catch(error =>{//handler 20 | console.error("promise is rejected with error: ", error); 21 | }); 22 | -------------------------------------------------------------------------------- /JsPractice/quickTipe.js: -------------------------------------------------------------------------------- 1 | //1. find unique values from array: spread operator 2 | const array = [1,2,3,2,3,2,5,6,2,7,7,7,7]; 3 | const uniqueArray = [...new Set(array)]; 4 | console.log(uniqueArray); 5 | 6 | //2. int to string: 7 | const num = 32; 8 | const numStr = num + '';//'32' 9 | console.log(numStr+10);//3210 10 | //or 11 | const numStr1 = String(num);//'32' 12 | console.log(numStr1+10); 13 | 14 | //3. float to int: 15 | const floatNum = 3.76; 16 | const intNum = parseInt(floatNum); 17 | console.log(intNum); 18 | 19 | //4. check if a variable is a Number: 20 | const value = '10'; 21 | if(typeof value === 'number' && !isNaN(value)){ 22 | console.log(value + ' is number'); 23 | } 24 | else{ 25 | console.log(value + ' is not a number'); 26 | 27 | } 28 | 29 | //5. swap variable values: 30 | let a = 5; 31 | let b = 10; 32 | [a,b] = [b,a]; 33 | console.log(a,b); 34 | 35 | //6. check if an Object has a property: 36 | const person = { 37 | name:'John', 38 | age : 28, 39 | } 40 | if(person.hasOwnProperty('address')){ 41 | console.log('person has property'); 42 | } 43 | 44 | //7. remove falsy value from the array: (false, 0, "", null, undefined, NaN): 45 | const values = [0,1,false,2,'',3,null,undefined,NaN,4]; 46 | const newVal = values.filter(Boolean); 47 | console.log(newVal); 48 | 49 | //8. String --> Uppercase, lower Case 50 | const str ='Naveen Automation Labs'; 51 | const u1 = str.toUpperCase(); // NAVEEN AUTOMATION LABS 52 | const l1 = str.toLowerCase();//naveen automation labs 53 | console.log(u1); 54 | console.log(l1); 55 | 56 | //9. check if Array contains a value: 57 | const lang = ['java', 'javascript', 'python', 'ruby']; 58 | if(lang.includes('javascript')){ 59 | console.log('found') 60 | } 61 | 62 | //10. check if an Array is Empty: 63 | const empty = []; 64 | if(empty.length === 0){ 65 | console.log("Array is empty"); 66 | } 67 | 68 | //11. generate a random number: 69 | const min = 10; 70 | const max= 200 ; 71 | const randomNumber = Math.floor(Math.random() * (max - min + 1))+ min; 72 | console.log(`Random Number : ${randomNumber}`); 73 | 74 | //12. String to number: 75 | const strNumber = '32.0'; 76 | const x1 = parseFloat(strNumber); 77 | console.log(x1); 78 | 79 | //13. Join array elements into a String: 80 | const words = ['Hello', 'Naveen']; 81 | const sentence = words.join(' '); 82 | console.log(sentence); 83 | 84 | //14. get object proeprty: 85 | const user = { 86 | name:'Tom', 87 | age: 25, 88 | dob: '01-01-1995' 89 | }; 90 | 91 | console.log(user['name']); 92 | console.log(user['dob']); 93 | 94 | //15. clone an array or object: 95 | const marks = [10,20,30,50,66,70]; 96 | const marksDuplicate = [...marks]; 97 | console.log(marksDuplicate); 98 | const userDuplicate = { ...user };//spread operator 99 | console.log(userDuplicate); 100 | 101 | //16. convert object to array: 102 | const employee = { 103 | name:'Tom', 104 | age: 25, 105 | dob: '01-01-1995' 106 | }; 107 | 108 | //a. keys array: 109 | const keysArray = Object.keys(employee); 110 | console.log(keysArray); 111 | 112 | //a. values array: 113 | const valuesArray = Object.values(employee); 114 | console.log(valuesArray); 115 | 116 | //c. key-value array: 117 | const keyValArray = Object.entries(employee); 118 | console.log(keyValArray); 119 | 120 | 121 | //17. get current date and time: 122 | const currentDate = new Date(); 123 | console.log(currentDate.toLocaleString()); 124 | 125 | //18. check variable is defined: 126 | let i; 127 | if(typeof i === 'undefined'){ 128 | console.log('variable not defined'); 129 | } 130 | 131 | //19. truncate an array: 132 | const testing = [0,1,2,3,4,5,6,7]; 133 | testing.length = 3; 134 | console.log(testing); 135 | 136 | //20. Last item in array: 137 | const pop = [0,1,2,3,4,5,6,7]; 138 | const n1 = pop.slice(-1); 139 | console.log(n1); -------------------------------------------------------------------------------- /JsPractice/reverseNumber.js: -------------------------------------------------------------------------------- 1 | //Reverse a Number: 2 | //12345 --> 54321/10 3 | function reverseNumber(num){//123 4 | //0-9: same number 5 | if(num>=0 && num<=9){ 6 | return num; 7 | } 8 | 9 | let reverseNum = 0; 10 | while(num!=0){//1 11 | reverseNum = reverseNum * 10 + (num % 10);//32*10+(1%10)=>320+1=321 12 | num = Math.floor(num/10);//123/10=12/10=1/10=0.1=>0 13 | } 14 | return reverseNum;//321 15 | } 16 | 17 | console.log(reverseNumber(123)); 18 | // console.log(reverseNumber(9)); 19 | // console.log(reverseNumber(123)); 20 | // console.log(reverseNumber(1234598999901)); 21 | //more test cases: 22 | console.log(reverseNumber(123)); 23 | 24 | // Creating a Map 25 | var myMap = new Map(); 26 | 27 | // Adding key-value pairs 28 | myMap.set("key1", "value1"); 29 | myMap.set("key2", "value2"); 30 | myMap.set("key4", "value22"); 31 | myMap.set("key4", "value222"); 32 | myMap.set(null,"naveen"); 33 | 34 | 35 | // Accessing values 36 | console.log(myMap.get("key1")); // Outputs: "value1" 37 | 38 | // Checking if a key exists 39 | console.log(myMap.has("key3")); // Outputs: false 40 | 41 | // Removing a key-value pair 42 | myMap.delete("key2"); 43 | console.log(myMap.get(null)); // Outputs: undefined, as "key2" has been removed 44 | myMap.forEach(function(k,v){ 45 | console.log(k+v); 46 | }); -------------------------------------------------------------------------------- /JsPractice/sample.txt: -------------------------------------------------------------------------------- 1 | hi naveen here how r u?? 2 | hi naveen here how r u?? 3 | hi naveen here how r u?? 4 | hi naveen here how r u?? 5 | hi naveen here how r u?? 6 | hi naveen here how r u?? 7 | hi naveen here how r u?? 8 | hi naveen here how r u?? 9 | hi naveen here how r u?? 10 | hi naveen here how r u?? 11 | hi naveen here how r u?? 12 | hi naveen here how r u?? 13 | hi naveen here how r u?? 14 | hi naveen here how r u?? 15 | hi naveen here how r u?? 16 | hi naveen here how r u?? 17 | hi naveen here how r u?? 18 | hi naveen here how r u?? 19 | hi naveen here how r u?? 20 | hi naveen here how r u?? 21 | hi naveen here how r u?? 22 | hi naveen here how r u?? 23 | hi naveen here how r u?? 24 | hi naveen here how r u?? 25 | 26 | -------------------------------------------------------------------------------- /JsPractice/staticConcept.js: -------------------------------------------------------------------------------- 1 | class Car{ 2 | static wheels = 4; 3 | constructor(name, model, price){ 4 | this.name = name; 5 | this.model = model; 6 | this.price = price; 7 | this.wheels = 50; 8 | } 9 | 10 | static stop(){ 11 | console.log("car -- stop") 12 | } 13 | 14 | drive(){ 15 | console.log(this.name + " is driving"); 16 | } 17 | } 18 | 19 | const c1 = new Car("Honda", 2023, 50); 20 | console.log(`${c1.name}, ${c1.model}, ${c1.price}, ${Car.wheels}`); 21 | console.log(Car.wheels) 22 | Car.stop(); 23 | //c1.stop();//error 24 | c1.drive(); 25 | //Car.drive();//error 26 | //console.log(wheels); 27 | 28 | //static var/function: call it by using class name 29 | //non static var/function: call it by using object reference name 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /JsPractice/stringmethods.js: -------------------------------------------------------------------------------- 1 | console.log("JavaScript".length); 2 | let str = "Naveen"; 3 | console.log(str.length); 4 | 5 | console.log("JavaScript"[2]); 6 | console.log("-----"); 7 | console.log("JavaScript".charAt(20)); 8 | console.log("-----"); 9 | 10 | 11 | console.log("JavaScript".charCodeAt(2)); 12 | //a-z: 97 to 122 13 | 14 | console.log("JavaScript".toLowerCase()); 15 | console.log("JavaScript".toUpperCase()); 16 | 17 | console.log("JavaScript".slice(2,-5));//vaS 18 | // JavaScript 19 | // 0123456789 20 | // -1 21 | //c=-5 and 5 22 | //t=9 and -1 23 | console.log("JavaScript".substring(2,6));//vaSc 24 | console.log("JavaScript".substring(-2,2));//-ve-->0,2--> Ja 25 | 26 | console.log("Naveen".concat(" Automation").concat(" Labs")); 27 | 28 | let lang = "Java_JavaScript_Python"; 29 | let arr = lang.split("_"); 30 | console.log(arr[0]); 31 | console.log(arr[2]); 32 | 33 | console.log("JavaScript".includes("Java")); 34 | console.log("JavaScript".includes("Hello")); 35 | 36 | console.log("Dev Test Framework Dev".replace("Dev", "JS")); 37 | console.log("Dev Test Framework Dev".replaceAll("Dev", "JS")); 38 | 39 | console.log("01-01-1990".replaceAll("-", "/")); 40 | 41 | console.log(" hello js ".trim()); 42 | console.log(" hello js ".trimStart()); 43 | console.log(" hello js ".trimEnd()); 44 | 45 | console.log("Dev".padEnd(10,"*")); 46 | console.log("Dev".padStart(10,"*")); 47 | 48 | console.log("Javascript".startsWith("J")); 49 | console.log("Java script".endsWith("script")); 50 | 51 | console.log("dev".repeat(3)); 52 | 53 | console.log("Naveen Automation Labs".indexOf("Automation"));//7 54 | console.log("Naveen Automation Labs".indexOf("N")); 55 | console.log("Naveen Automation Labs".indexOf("JS")); 56 | 57 | console.log("Naveen Automation Labs Naveen".lastIndexOf("Naveen")); 58 | 59 | console.log("Naveen Automation Labs".search("Automation"));//7 -------------------------------------------------------------------------------- /JsPractice/switchcase.js: -------------------------------------------------------------------------------- 1 | function checkDayOfWeek(dayNumber){ 2 | let day; 3 | switch (dayNumber) { 4 | case 0: 5 | day = "Sunday"; 6 | break; 7 | case 1: 8 | day = "Monday"; 9 | break; 10 | case 2: 11 | day = "Tuesday"; 12 | break; 13 | case 3: 14 | day = "Wednesday"; 15 | break; 16 | case 4: 17 | day = "Thursday"; 18 | break; 19 | case 5: 20 | day = "Friday"; 21 | break; 22 | case 6: 23 | day = "Saturday"; 24 | break; 25 | 26 | default: 27 | console.log("Invalid day"); 28 | break; 29 | } 30 | 31 | return day; 32 | } 33 | 34 | console.log(checkDayOfWeek(4)); 35 | // console.log(checkDayOfWeek(3)); 36 | // console.log(checkDayOfWeek(6)); 37 | // console.log(checkDayOfWeek(10)); 38 | 39 | 40 | 41 | 42 | // 43 | let browser = "chrome"; 44 | switch (browser) { 45 | case "chrome": 46 | console.log("launch chrome"); 47 | break; 48 | case "firefox": 49 | console.log("launch firefox"); 50 | break; 51 | case "edge": 52 | console.log("launch edge"); 53 | break; 54 | 55 | default: 56 | console.log("plz pass the right browser...." + browser); 57 | break; 58 | } 59 | 60 | //multi env: dev, qa, stage, uat, prod 61 | //multi user: admin, customer, seller, distributor, cat manager -------------------------------------------------------------------------------- /JsPractice/sync.js: -------------------------------------------------------------------------------- 1 | //sync vs async behaviour: 2 | //1 -- done -- > fetch 100 users from the API/DB -- 20 secs 3 | //2 -- done -- display user profile -- 10 secs 4 | //3 -- done 5 | //4 -- done 6 | //end 7 | ///blocking behaviour for the user 8 | 9 | // console.log("start"); 10 | // for(let i=0; i<30000; i++){ 11 | // console.log(i); 12 | // } 13 | // console.log("end"); 14 | 15 | //Async: 16 | //1 -- fetch user -- 100 users are coming from API/DB --> 20 secs --> callback function: Promises 17 | //2 -- display user profile -- 10 secs 18 | //3 -- fetch order info -- 5 secs 19 | //4 -- do something else 20 | console.log("start"); 21 | setTimeout(()=>{ 22 | console.log("time out is done"); 23 | }, 10000); 24 | console.log("end"); 25 | console.log("end"); 26 | console.log("end"); 27 | console.log("end"); 28 | console.log("end"); 29 | -------------------------------------------------------------------------------- /JsPractice/templateliterals.js: -------------------------------------------------------------------------------- 1 | const name = "Naveen"; 2 | //backticks => `` 3 | const age = 30; 4 | //vars: ${varname} 5 | const mesg = `hello, my name is ${name} and age is ${age}`; 6 | console.log(mesg); 7 | 8 | const multiLine = `hi this is my javascript code 9 | and im so happy 10 | and I want to be perfect in JS 11 | ohh yes!`; 12 | console.log(multiLine); 13 | 14 | const a = 10; 15 | const b = 20; 16 | const result = `the addition of ${a} and ${b} is ${a+b}`; 17 | console.log(result); 18 | 19 | 20 | function getXpath(name){ 21 | return `//input[@id='${name}']`; 22 | } 23 | console.log(getXpath('Tom\'s')); -------------------------------------------------------------------------------- /JsPractice/typeOfConcept.js: -------------------------------------------------------------------------------- 1 | let x = 30; 2 | console.log(typeof x); 3 | 4 | x = "Hello"; 5 | console.log(typeof x); 6 | 7 | x = { 8 | name: 'John', 9 | } 10 | console.log(typeof x); 11 | 12 | let flag = true; 13 | console.log(typeof flag); 14 | let type = typeof flag; 15 | 16 | const arr = [1,2,3,4,5]; 17 | console.log(typeof arr); 18 | 19 | const j = null; 20 | console.log(typeof j); 21 | 22 | let y; 23 | console.log(typeof y); 24 | 25 | 26 | 27 | function print(name){ 28 | console.log("My Name is "+name); 29 | } 30 | 31 | console.log(typeof print);"function" 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /JsPractice/variables.js: -------------------------------------------------------------------------------- 1 | //1. var: old way 2 | //ES6 3 | //scope: var 4 | //functionally/locallly + global scope 5 | 6 | var x = 10; 7 | function test(){ 8 | var y = 20; 9 | } 10 | console.log(x); 11 | 12 | var pop = "hi js"; 13 | function rel(){ 14 | var top = "hello js"; 15 | } 16 | rel(); 17 | console.log(pop); 18 | //console.log(top); 19 | 20 | var browser = "chrome"; 21 | var browser = "firefox"; 22 | browser = "edge"; 23 | console.log(browser); 24 | 25 | ////// 26 | var g; 27 | console.log(g);//undefined 28 | g = "hello world"; 29 | console.log(g); 30 | 31 | //issue with var: 32 | var flag = "hey naveen"; 33 | var t1 = 4; 34 | if(t1 > 3){ 35 | var flag = "hey tom"; 36 | } 37 | console.log(flag); 38 | 39 | //let : 40 | //scope: block scoped 41 | //{} 42 | let m = "hey naveen"; 43 | let time = 4; 44 | if(time > 3){ 45 | let mesg = "hey hw r u?"; 46 | console.log(mesg); 47 | } 48 | //console.log(mesg); 49 | console.log(m); 50 | 51 | // 52 | let len = 4; 53 | len = 5; 54 | console.log(len); 55 | 56 | //const: 57 | const mg = "hey naveen"; 58 | //mg = "hey tom"; 59 | console.log(mg); 60 | 61 | const days = 7; 62 | //days = 10; 63 | console.log(100 * days); 64 | 65 | // 66 | const p = 10; 67 | console.log(p); 68 | 69 | 70 | var hh = 10; 71 | var hh = 20; 72 | 73 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pw-demo", 3 | "version": "1.0.0", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "pw-demo", 9 | "version": "1.0.0", 10 | "license": "ISC", 11 | "dependencies": { 12 | "node-fetch": "^3.3.2" 13 | }, 14 | "devDependencies": { 15 | "@playwright/test": "^1.36.1" 16 | } 17 | }, 18 | "node_modules/@playwright/test": { 19 | "version": "1.36.1", 20 | "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.36.1.tgz", 21 | "integrity": "sha512-YK7yGWK0N3C2QInPU6iaf/L3N95dlGdbsezLya4n0ZCh3IL7VgPGxC6Gnznh9ApWdOmkJeleT2kMTcWPRZvzqg==", 22 | "dev": true, 23 | "dependencies": { 24 | "@types/node": "*", 25 | "playwright-core": "1.36.1" 26 | }, 27 | "bin": { 28 | "playwright": "cli.js" 29 | }, 30 | "engines": { 31 | "node": ">=16" 32 | }, 33 | "optionalDependencies": { 34 | "fsevents": "2.3.2" 35 | } 36 | }, 37 | "node_modules/@types/node": { 38 | "version": "20.4.2", 39 | "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.2.tgz", 40 | "integrity": "sha512-Dd0BYtWgnWJKwO1jkmTrzofjK2QXXcai0dmtzvIBhcA+RsG5h8R3xlyta0kGOZRNfL9GuRtb1knmPEhQrePCEw==", 41 | "dev": true 42 | }, 43 | "node_modules/data-uri-to-buffer": { 44 | "version": "4.0.1", 45 | "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", 46 | "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", 47 | "engines": { 48 | "node": ">= 12" 49 | } 50 | }, 51 | "node_modules/fetch-blob": { 52 | "version": "3.2.0", 53 | "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", 54 | "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", 55 | "funding": [ 56 | { 57 | "type": "github", 58 | "url": "https://github.com/sponsors/jimmywarting" 59 | }, 60 | { 61 | "type": "paypal", 62 | "url": "https://paypal.me/jimmywarting" 63 | } 64 | ], 65 | "dependencies": { 66 | "node-domexception": "^1.0.0", 67 | "web-streams-polyfill": "^3.0.3" 68 | }, 69 | "engines": { 70 | "node": "^12.20 || >= 14.13" 71 | } 72 | }, 73 | "node_modules/formdata-polyfill": { 74 | "version": "4.0.10", 75 | "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", 76 | "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", 77 | "dependencies": { 78 | "fetch-blob": "^3.1.2" 79 | }, 80 | "engines": { 81 | "node": ">=12.20.0" 82 | } 83 | }, 84 | "node_modules/fsevents": { 85 | "version": "2.3.2", 86 | "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", 87 | "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", 88 | "dev": true, 89 | "hasInstallScript": true, 90 | "optional": true, 91 | "os": [ 92 | "darwin" 93 | ], 94 | "engines": { 95 | "node": "^8.16.0 || ^10.6.0 || >=11.0.0" 96 | } 97 | }, 98 | "node_modules/node-domexception": { 99 | "version": "1.0.0", 100 | "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", 101 | "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", 102 | "funding": [ 103 | { 104 | "type": "github", 105 | "url": "https://github.com/sponsors/jimmywarting" 106 | }, 107 | { 108 | "type": "github", 109 | "url": "https://paypal.me/jimmywarting" 110 | } 111 | ], 112 | "engines": { 113 | "node": ">=10.5.0" 114 | } 115 | }, 116 | "node_modules/node-fetch": { 117 | "version": "3.3.2", 118 | "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", 119 | "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", 120 | "dependencies": { 121 | "data-uri-to-buffer": "^4.0.0", 122 | "fetch-blob": "^3.1.4", 123 | "formdata-polyfill": "^4.0.10" 124 | }, 125 | "engines": { 126 | "node": "^12.20.0 || ^14.13.1 || >=16.0.0" 127 | }, 128 | "funding": { 129 | "type": "opencollective", 130 | "url": "https://opencollective.com/node-fetch" 131 | } 132 | }, 133 | "node_modules/playwright-core": { 134 | "version": "1.36.1", 135 | "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.36.1.tgz", 136 | "integrity": "sha512-7+tmPuMcEW4xeCL9cp9KxmYpQYHKkyjwoXRnoeTowaeNat8PoBMk/HwCYhqkH2fRkshfKEOiVus/IhID2Pg8kg==", 137 | "dev": true, 138 | "bin": { 139 | "playwright-core": "cli.js" 140 | }, 141 | "engines": { 142 | "node": ">=16" 143 | } 144 | }, 145 | "node_modules/web-streams-polyfill": { 146 | "version": "3.2.1", 147 | "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", 148 | "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==", 149 | "engines": { 150 | "node": ">= 8" 151 | } 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pw-demo", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": {}, 7 | "keywords": [], 8 | "author": "", 9 | "license": "ISC", 10 | "devDependencies": { 11 | "@playwright/test": "^1.36.1" 12 | }, 13 | "dependencies": { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /playwright.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig, devices } from '@playwright/test'; 2 | 3 | /** 4 | * Read environment variables from file. 5 | * https://github.com/motdotla/dotenv 6 | */ 7 | // require('dotenv').config(); 8 | 9 | /** 10 | * See https://playwright.dev/docs/test-configuration. 11 | */ 12 | export default defineConfig({ 13 | testDir: './tests', 14 | /* Run tests in files in parallel */ 15 | fullyParallel: true, 16 | /* Fail the build on CI if you accidentally left test.only in the source code. */ 17 | forbidOnly: !!process.env.CI, 18 | /* Retry on CI only */ 19 | retries: process.env.CI ? 2 : 0, 20 | /* Opt out of parallel tests on CI. */ 21 | workers: process.env.CI ? 1 : undefined, 22 | /* Reporter to use. See https://playwright.dev/docs/test-reporters */ 23 | reporter: 'html', 24 | /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ 25 | use: { 26 | /* Base URL to use in actions like `await page.goto('/')`. */ 27 | // baseURL: 'http://127.0.0.1:3000', 28 | 29 | /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ 30 | trace: 'on-first-retry', 31 | }, 32 | 33 | /* Configure projects for major browsers */ 34 | projects: [ 35 | { 36 | name: 'chromium', 37 | use: { ...devices['Desktop Chrome'] }, 38 | }, 39 | 40 | { 41 | name: 'firefox', 42 | use: { ...devices['Desktop Firefox'] }, 43 | }, 44 | 45 | { 46 | name: 'webkit', 47 | use: { ...devices['Desktop Safari'] }, 48 | }, 49 | 50 | /* Test against mobile viewports. */ 51 | // { 52 | // name: 'Mobile Chrome', 53 | // use: { ...devices['Pixel 5'] }, 54 | // }, 55 | // { 56 | // name: 'Mobile Safari', 57 | // use: { ...devices['iPhone 12'] }, 58 | // }, 59 | 60 | /* Test against branded browsers. */ 61 | // { 62 | // name: 'Microsoft Edge', 63 | // use: { ...devices['Desktop Edge'], channel: 'msedge' }, 64 | // }, 65 | // { 66 | // name: 'Google Chrome', 67 | // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, 68 | // }, 69 | ], 70 | 71 | /* Run your local dev server before starting the tests */ 72 | // webServer: { 73 | // command: 'npm run start', 74 | // url: 'http://127.0.0.1:3000', 75 | // reuseExistingServer: !process.env.CI, 76 | // }, 77 | }); 78 | -------------------------------------------------------------------------------- /tests-examples/demo-todo-app.spec.ts: -------------------------------------------------------------------------------- 1 | import { test, expect, type Page } from '@playwright/test'; 2 | 3 | test.beforeEach(async ({ page }) => { 4 | await page.goto('https://demo.playwright.dev/todomvc'); 5 | }); 6 | 7 | const TODO_ITEMS = [ 8 | 'buy some cheese', 9 | 'feed the cat', 10 | 'book a doctors appointment' 11 | ]; 12 | 13 | test.describe('New Todo', () => { 14 | test('should allow me to add todo items', async ({ page }) => { 15 | // create a new todo locator 16 | const newTodo = page.getByPlaceholder('What needs to be done?'); 17 | 18 | // Create 1st todo. 19 | await newTodo.fill(TODO_ITEMS[0]); 20 | await newTodo.press('Enter'); 21 | 22 | // Make sure the list only has one todo item. 23 | await expect(page.getByTestId('todo-title')).toHaveText([ 24 | TODO_ITEMS[0] 25 | ]); 26 | 27 | // Create 2nd todo. 28 | await newTodo.fill(TODO_ITEMS[1]); 29 | await newTodo.press('Enter'); 30 | 31 | // Make sure the list now has two todo items. 32 | await expect(page.getByTestId('todo-title')).toHaveText([ 33 | TODO_ITEMS[0], 34 | TODO_ITEMS[1] 35 | ]); 36 | 37 | await checkNumberOfTodosInLocalStorage(page, 2); 38 | }); 39 | 40 | test('should clear text input field when an item is added', async ({ page }) => { 41 | // create a new todo locator 42 | const newTodo = page.getByPlaceholder('What needs to be done?'); 43 | 44 | // Create one todo item. 45 | await newTodo.fill(TODO_ITEMS[0]); 46 | await newTodo.press('Enter'); 47 | 48 | // Check that input is empty. 49 | await expect(newTodo).toBeEmpty(); 50 | await checkNumberOfTodosInLocalStorage(page, 1); 51 | }); 52 | 53 | test('should append new items to the bottom of the list', async ({ page }) => { 54 | // Create 3 items. 55 | await createDefaultTodos(page); 56 | 57 | // create a todo count locator 58 | const todoCount = page.getByTestId('todo-count') 59 | 60 | // Check test using different methods. 61 | await expect(page.getByText('3 items left')).toBeVisible(); 62 | await expect(todoCount).toHaveText('3 items left'); 63 | await expect(todoCount).toContainText('3'); 64 | await expect(todoCount).toHaveText(/3/); 65 | 66 | // Check all items in one call. 67 | await expect(page.getByTestId('todo-title')).toHaveText(TODO_ITEMS); 68 | await checkNumberOfTodosInLocalStorage(page, 3); 69 | }); 70 | }); 71 | 72 | test.describe('Mark all as completed', () => { 73 | test.beforeEach(async ({ page }) => { 74 | await createDefaultTodos(page); 75 | await checkNumberOfTodosInLocalStorage(page, 3); 76 | }); 77 | 78 | test.afterEach(async ({ page }) => { 79 | await checkNumberOfTodosInLocalStorage(page, 3); 80 | }); 81 | 82 | test('should allow me to mark all items as completed', async ({ page }) => { 83 | // Complete all todos. 84 | await page.getByLabel('Mark all as complete').check(); 85 | 86 | // Ensure all todos have 'completed' class. 87 | await expect(page.getByTestId('todo-item')).toHaveClass(['completed', 'completed', 'completed']); 88 | await checkNumberOfCompletedTodosInLocalStorage(page, 3); 89 | }); 90 | 91 | test('should allow me to clear the complete state of all items', async ({ page }) => { 92 | const toggleAll = page.getByLabel('Mark all as complete'); 93 | // Check and then immediately uncheck. 94 | await toggleAll.check(); 95 | await toggleAll.uncheck(); 96 | 97 | // Should be no completed classes. 98 | await expect(page.getByTestId('todo-item')).toHaveClass(['', '', '']); 99 | }); 100 | 101 | test('complete all checkbox should update state when items are completed / cleared', async ({ page }) => { 102 | const toggleAll = page.getByLabel('Mark all as complete'); 103 | await toggleAll.check(); 104 | await expect(toggleAll).toBeChecked(); 105 | await checkNumberOfCompletedTodosInLocalStorage(page, 3); 106 | 107 | // Uncheck first todo. 108 | const firstTodo = page.getByTestId('todo-item').nth(0); 109 | await firstTodo.getByRole('checkbox').uncheck(); 110 | 111 | // Reuse toggleAll locator and make sure its not checked. 112 | await expect(toggleAll).not.toBeChecked(); 113 | 114 | await firstTodo.getByRole('checkbox').check(); 115 | await checkNumberOfCompletedTodosInLocalStorage(page, 3); 116 | 117 | // Assert the toggle all is checked again. 118 | await expect(toggleAll).toBeChecked(); 119 | }); 120 | }); 121 | 122 | test.describe('Item', () => { 123 | 124 | test('should allow me to mark items as complete', async ({ page }) => { 125 | // create a new todo locator 126 | const newTodo = page.getByPlaceholder('What needs to be done?'); 127 | 128 | // Create two items. 129 | for (const item of TODO_ITEMS.slice(0, 2)) { 130 | await newTodo.fill(item); 131 | await newTodo.press('Enter'); 132 | } 133 | 134 | // Check first item. 135 | const firstTodo = page.getByTestId('todo-item').nth(0); 136 | await firstTodo.getByRole('checkbox').check(); 137 | await expect(firstTodo).toHaveClass('completed'); 138 | 139 | // Check second item. 140 | const secondTodo = page.getByTestId('todo-item').nth(1); 141 | await expect(secondTodo).not.toHaveClass('completed'); 142 | await secondTodo.getByRole('checkbox').check(); 143 | 144 | // Assert completed class. 145 | await expect(firstTodo).toHaveClass('completed'); 146 | await expect(secondTodo).toHaveClass('completed'); 147 | }); 148 | 149 | test('should allow me to un-mark items as complete', async ({ page }) => { 150 | // create a new todo locator 151 | const newTodo = page.getByPlaceholder('What needs to be done?'); 152 | 153 | // Create two items. 154 | for (const item of TODO_ITEMS.slice(0, 2)) { 155 | await newTodo.fill(item); 156 | await newTodo.press('Enter'); 157 | } 158 | 159 | const firstTodo = page.getByTestId('todo-item').nth(0); 160 | const secondTodo = page.getByTestId('todo-item').nth(1); 161 | const firstTodoCheckbox = firstTodo.getByRole('checkbox'); 162 | 163 | await firstTodoCheckbox.check(); 164 | await expect(firstTodo).toHaveClass('completed'); 165 | await expect(secondTodo).not.toHaveClass('completed'); 166 | await checkNumberOfCompletedTodosInLocalStorage(page, 1); 167 | 168 | await firstTodoCheckbox.uncheck(); 169 | await expect(firstTodo).not.toHaveClass('completed'); 170 | await expect(secondTodo).not.toHaveClass('completed'); 171 | await checkNumberOfCompletedTodosInLocalStorage(page, 0); 172 | }); 173 | 174 | test('should allow me to edit an item', async ({ page }) => { 175 | await createDefaultTodos(page); 176 | 177 | const todoItems = page.getByTestId('todo-item'); 178 | const secondTodo = todoItems.nth(1); 179 | await secondTodo.dblclick(); 180 | await expect(secondTodo.getByRole('textbox', { name: 'Edit' })).toHaveValue(TODO_ITEMS[1]); 181 | await secondTodo.getByRole('textbox', { name: 'Edit' }).fill('buy some sausages'); 182 | await secondTodo.getByRole('textbox', { name: 'Edit' }).press('Enter'); 183 | 184 | // Explicitly assert the new text value. 185 | await expect(todoItems).toHaveText([ 186 | TODO_ITEMS[0], 187 | 'buy some sausages', 188 | TODO_ITEMS[2] 189 | ]); 190 | await checkTodosInLocalStorage(page, 'buy some sausages'); 191 | }); 192 | }); 193 | 194 | test.describe('Editing', () => { 195 | test.beforeEach(async ({ page }) => { 196 | await createDefaultTodos(page); 197 | await checkNumberOfTodosInLocalStorage(page, 3); 198 | }); 199 | 200 | test('should hide other controls when editing', async ({ page }) => { 201 | const todoItem = page.getByTestId('todo-item').nth(1); 202 | await todoItem.dblclick(); 203 | await expect(todoItem.getByRole('checkbox')).not.toBeVisible(); 204 | await expect(todoItem.locator('label', { 205 | hasText: TODO_ITEMS[1], 206 | })).not.toBeVisible(); 207 | await checkNumberOfTodosInLocalStorage(page, 3); 208 | }); 209 | 210 | test('should save edits on blur', async ({ page }) => { 211 | const todoItems = page.getByTestId('todo-item'); 212 | await todoItems.nth(1).dblclick(); 213 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages'); 214 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).dispatchEvent('blur'); 215 | 216 | await expect(todoItems).toHaveText([ 217 | TODO_ITEMS[0], 218 | 'buy some sausages', 219 | TODO_ITEMS[2], 220 | ]); 221 | await checkTodosInLocalStorage(page, 'buy some sausages'); 222 | }); 223 | 224 | test('should trim entered text', async ({ page }) => { 225 | const todoItems = page.getByTestId('todo-item'); 226 | await todoItems.nth(1).dblclick(); 227 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill(' buy some sausages '); 228 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter'); 229 | 230 | await expect(todoItems).toHaveText([ 231 | TODO_ITEMS[0], 232 | 'buy some sausages', 233 | TODO_ITEMS[2], 234 | ]); 235 | await checkTodosInLocalStorage(page, 'buy some sausages'); 236 | }); 237 | 238 | test('should remove the item if an empty text string was entered', async ({ page }) => { 239 | const todoItems = page.getByTestId('todo-item'); 240 | await todoItems.nth(1).dblclick(); 241 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill(''); 242 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter'); 243 | 244 | await expect(todoItems).toHaveText([ 245 | TODO_ITEMS[0], 246 | TODO_ITEMS[2], 247 | ]); 248 | }); 249 | 250 | test('should cancel edits on escape', async ({ page }) => { 251 | const todoItems = page.getByTestId('todo-item'); 252 | await todoItems.nth(1).dblclick(); 253 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages'); 254 | await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Escape'); 255 | await expect(todoItems).toHaveText(TODO_ITEMS); 256 | }); 257 | }); 258 | 259 | test.describe('Counter', () => { 260 | test('should display the current number of todo items', async ({ page }) => { 261 | // create a new todo locator 262 | const newTodo = page.getByPlaceholder('What needs to be done?'); 263 | 264 | // create a todo count locator 265 | const todoCount = page.getByTestId('todo-count') 266 | 267 | await newTodo.fill(TODO_ITEMS[0]); 268 | await newTodo.press('Enter'); 269 | 270 | await expect(todoCount).toContainText('1'); 271 | 272 | await newTodo.fill(TODO_ITEMS[1]); 273 | await newTodo.press('Enter'); 274 | await expect(todoCount).toContainText('2'); 275 | 276 | await checkNumberOfTodosInLocalStorage(page, 2); 277 | }); 278 | }); 279 | 280 | test.describe('Clear completed button', () => { 281 | test.beforeEach(async ({ page }) => { 282 | await createDefaultTodos(page); 283 | }); 284 | 285 | test('should display the correct text', async ({ page }) => { 286 | await page.locator('.todo-list li .toggle').first().check(); 287 | await expect(page.getByRole('button', { name: 'Clear completed' })).toBeVisible(); 288 | }); 289 | 290 | test('should remove completed items when clicked', async ({ page }) => { 291 | const todoItems = page.getByTestId('todo-item'); 292 | await todoItems.nth(1).getByRole('checkbox').check(); 293 | await page.getByRole('button', { name: 'Clear completed' }).click(); 294 | await expect(todoItems).toHaveCount(2); 295 | await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]); 296 | }); 297 | 298 | test('should be hidden when there are no items that are completed', async ({ page }) => { 299 | await page.locator('.todo-list li .toggle').first().check(); 300 | await page.getByRole('button', { name: 'Clear completed' }).click(); 301 | await expect(page.getByRole('button', { name: 'Clear completed' })).toBeHidden(); 302 | }); 303 | }); 304 | 305 | test.describe('Persistence', () => { 306 | test('should persist its data', async ({ page }) => { 307 | // create a new todo locator 308 | const newTodo = page.getByPlaceholder('What needs to be done?'); 309 | 310 | for (const item of TODO_ITEMS.slice(0, 2)) { 311 | await newTodo.fill(item); 312 | await newTodo.press('Enter'); 313 | } 314 | 315 | const todoItems = page.getByTestId('todo-item'); 316 | const firstTodoCheck = todoItems.nth(0).getByRole('checkbox'); 317 | await firstTodoCheck.check(); 318 | await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]); 319 | await expect(firstTodoCheck).toBeChecked(); 320 | await expect(todoItems).toHaveClass(['completed', '']); 321 | 322 | // Ensure there is 1 completed item. 323 | await checkNumberOfCompletedTodosInLocalStorage(page, 1); 324 | 325 | // Now reload. 326 | await page.reload(); 327 | await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]); 328 | await expect(firstTodoCheck).toBeChecked(); 329 | await expect(todoItems).toHaveClass(['completed', '']); 330 | }); 331 | }); 332 | 333 | test.describe('Routing', () => { 334 | test.beforeEach(async ({ page }) => { 335 | await createDefaultTodos(page); 336 | // make sure the app had a chance to save updated todos in storage 337 | // before navigating to a new view, otherwise the items can get lost :( 338 | // in some frameworks like Durandal 339 | await checkTodosInLocalStorage(page, TODO_ITEMS[0]); 340 | }); 341 | 342 | test('should allow me to display active items', async ({ page }) => { 343 | const todoItem = page.getByTestId('todo-item'); 344 | await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); 345 | 346 | await checkNumberOfCompletedTodosInLocalStorage(page, 1); 347 | await page.getByRole('link', { name: 'Active' }).click(); 348 | await expect(todoItem).toHaveCount(2); 349 | await expect(todoItem).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]); 350 | }); 351 | 352 | test('should respect the back button', async ({ page }) => { 353 | const todoItem = page.getByTestId('todo-item'); 354 | await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); 355 | 356 | await checkNumberOfCompletedTodosInLocalStorage(page, 1); 357 | 358 | await test.step('Showing all items', async () => { 359 | await page.getByRole('link', { name: 'All' }).click(); 360 | await expect(todoItem).toHaveCount(3); 361 | }); 362 | 363 | await test.step('Showing active items', async () => { 364 | await page.getByRole('link', { name: 'Active' }).click(); 365 | }); 366 | 367 | await test.step('Showing completed items', async () => { 368 | await page.getByRole('link', { name: 'Completed' }).click(); 369 | }); 370 | 371 | await expect(todoItem).toHaveCount(1); 372 | await page.goBack(); 373 | await expect(todoItem).toHaveCount(2); 374 | await page.goBack(); 375 | await expect(todoItem).toHaveCount(3); 376 | }); 377 | 378 | test('should allow me to display completed items', async ({ page }) => { 379 | await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); 380 | await checkNumberOfCompletedTodosInLocalStorage(page, 1); 381 | await page.getByRole('link', { name: 'Completed' }).click(); 382 | await expect(page.getByTestId('todo-item')).toHaveCount(1); 383 | }); 384 | 385 | test('should allow me to display all items', async ({ page }) => { 386 | await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); 387 | await checkNumberOfCompletedTodosInLocalStorage(page, 1); 388 | await page.getByRole('link', { name: 'Active' }).click(); 389 | await page.getByRole('link', { name: 'Completed' }).click(); 390 | await page.getByRole('link', { name: 'All' }).click(); 391 | await expect(page.getByTestId('todo-item')).toHaveCount(3); 392 | }); 393 | 394 | test('should highlight the currently applied filter', async ({ page }) => { 395 | await expect(page.getByRole('link', { name: 'All' })).toHaveClass('selected'); 396 | 397 | //create locators for active and completed links 398 | const activeLink = page.getByRole('link', { name: 'Active' }); 399 | const completedLink = page.getByRole('link', { name: 'Completed' }); 400 | await activeLink.click(); 401 | 402 | // Page change - active items. 403 | await expect(activeLink).toHaveClass('selected'); 404 | await completedLink.click(); 405 | 406 | // Page change - completed items. 407 | await expect(completedLink).toHaveClass('selected'); 408 | }); 409 | }); 410 | 411 | async function createDefaultTodos(page: Page) { 412 | // create a new todo locator 413 | const newTodo = page.getByPlaceholder('What needs to be done?'); 414 | 415 | for (const item of TODO_ITEMS) { 416 | await newTodo.fill(item); 417 | await newTodo.press('Enter'); 418 | } 419 | } 420 | 421 | async function checkNumberOfTodosInLocalStorage(page: Page, expected: number) { 422 | return await page.waitForFunction(e => { 423 | return JSON.parse(localStorage['react-todos']).length === e; 424 | }, expected); 425 | } 426 | 427 | async function checkNumberOfCompletedTodosInLocalStorage(page: Page, expected: number) { 428 | return await page.waitForFunction(e => { 429 | return JSON.parse(localStorage['react-todos']).filter((todo: any) => todo.completed).length === e; 430 | }, expected); 431 | } 432 | 433 | async function checkTodosInLocalStorage(page: Page, title: string) { 434 | return await page.waitForFunction(t => { 435 | return JSON.parse(localStorage['react-todos']).map((todo: any) => todo.title).includes(t); 436 | }, title); 437 | } 438 | -------------------------------------------------------------------------------- /tests/example.spec.ts: -------------------------------------------------------------------------------- 1 | import { test, expect } from '@playwright/test'; 2 | 3 | test('has title', async ({ page }) => { 4 | await page.goto('https://playwright.dev/'); 5 | 6 | // Expect a title "to contain" a substring. 7 | await expect(page).toHaveTitle(/Playwright/); 8 | }); 9 | 10 | test('get started link', async ({ page }) => { 11 | await page.goto('https://playwright.dev/'); 12 | 13 | // Click the get started link. 14 | await page.getByRole('link', { name: 'Get started' }).click(); 15 | 16 | // Expects the URL to contain intro. 17 | await expect(page).toHaveURL(/.*intro/); 18 | }); 19 | --------------------------------------------------------------------------------