vita-playwright
TypeScript icon, indicating that this package has built-in type declarations

1.5.1-Beta-7-report-update-5 • Public • Published

VITA Playwright Helpers

VITA Playwright helpers are written in Typescript with playwright support and a focus on using common playwright helpers, Excel utilities and Pdf utilities.

Table of Contents

Installation

Node.js

npm install vita-playwright

Note that vita-playwright uses ES6 features so only Node.js v4+ is supported.

Helpers

vita-playwright has an extensive methods for working with playwright, excel and pdf. This section reviews the most common functions and use cases. Examples can also be found in the examples directory of the source code.

Api Helpers

To use most common API methods, you first require ApiHelper class. Then you can access methods within the ApiHelper class to use API calls.

import {ApiHelper} from 'vita-playwright';

// call static methods using classname
const getResponse = await ApiHelper.get(url, header);
const putResponse = await ApiHelper.put(url, header, payload);
const postResponse = await ApiHelper.post(url, header, payload);

ApiHelpers.post

/**
 * @description: Post call with endpoint, headers and data.
 * @param {string}  apiEndPoint - API end point.
 * @param {string}  headers  - headers contains authentication keys, application type etc..
 * @param {string}  payload  - payload data
 * @returns {Promise<reponse>} - returns Promise of reponse
 */
import { ApiHelper } from "vita-playwright";
const headers= {
        "content-type": "application/json; charset=utf-8",
        "Accept": "*/*"
        };
const payload = {
  "key":"value"
};
const apiEndPoint = "https://admin.googleapis.com/discovery/rest?version=datatransfer_v1";

await ApiHelper.post(
        apiEndPoint,
        headers,
        payload
      );

ApiHelpers.get

/**
 * @description: Get call with endpoint and headers.
 * @param {string}  apiEndPoint - API end point.
 * @param {string}  headers  - headers contains authentication keys, application type etc..
 * @returns {Promise<reponse>} - returns Promise of reponse
 */
import { ApiHelper } from "vita-playwright";
const headers= {
        "content-type": "application/json; charset=utf-8",
        "Accept": "*/*"
        };
const apiEndPoint = "https://admin.googleapis.com/discovery/rest?version=datatransfer_v1";

await ApiHelper.get(
        apiEndPoint,
        headers,
      );

ApiHelpers.put

/**
 * @description: Put call with endpoint, headers and data and it will insert the data.
 * @param {string}  apiEndPoint - API end point.
 * @param {string}  headers  - headers contains authentication keys, application type etc..
 * @param {string}  payload  - payload data
 * @returns {Promise<reponse>} - returns Promise of reponse
 */
import { ApiHelper } from "vita-playwright";
const headers= {
        "content-type": "application/json; charset=utf-8",
        "Accept": "*/*"
        };
const data = {
  "key":"value"
};
const apiEndPoint = "https://admin.googleapis.com/discovery/rest?version=datatransfer_v1";

await ApiHelper.put(
        apiEndPoint,
        headers,
        data
      );

UI Helpers

Either you can create object or extends UIHelper to use common ui helpers by passing locators

import {UIHelper} from 'vita-playwright';

const uihelper = new UIHelpers();
// call static methods using classname
await uihelper.filltheData(locator, data);
await uihelper.clickonWebElement(locator);
await uihelper.getInnerHTML(locator);
await uihelper.getInnerText(locator);
await uihelper.getText(locator);
await uihelper.getAttribute(locator, attribute);
await uihelper.evaluateJS(jsDOM);
const isElementPresent = await uihelper.isElementPresent(locator);
const isElementEnabled = await uihelper.isElementEnabled(locator);
await waitTillElementIsVisible(elementSelector, waitTime);
const inputBoxValue = await uihelper.getIputBoxValue(locator);
await downloadAFile(downloadButton, downloadFilePath);
await uploadAFile(uploadButton, uploadFilePath);
const elementReference = await getElementRefByRole(roleType, roleName);

Note: getElementRefByRole() method will work for all types of roles, example: button, combobox, main, checkbox and radiobutton.

filltheData

/**
 * @description: sets the text in inputbox.
 * @param {string}  locator - css selector/xpath of the inputbox.
 * @param {string}  data  - Text to be set to inputbox
 * @returns {Promise<void>} - returns Promise of void
 */
async filltheData(locator: any, data: any);

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  await this.filltheData("locator/xpath/css selector", "data to set into inputbox");
}

clickonWebElement

/**
 * @description: click the given locator element.
 * @param {string}  locator - css selector/xpath of the element.
 * @returns {Promise<void>} - returns Promise of void
 */
async clickonWebElement(locator: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  await this.clickonWebElement("locator/xpath/css selector");
}

getInnerHTML

/**
 * @description: returns inner html of locator element.
 * @param {string}  locator - css selector/xpath of the element.
 * @returns {string} - returns inner html string
 */
async getInnerHTML(locator: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  console.log(await this.getInnerHTML("locator/xpath/css selector"));
  //output: inner HTML of given selector
}

getInnerText

/**
 * @description: returns inner text of locator element.
 * @param {string}  locator - css selector/xpath of the element.
 * @returns {string} - returns inner text string
 */
async getInnerText(locator: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  console.log(await this.getInnerText("locator/xpath/css selector"));
  //output: inner Text of given selector
}

getText

/**
 * @description: returns text of locator element.
 * @param {string}  locator - css selector/xpath of the element.
 * @returns {string} - returns text string
 */
async getText(locator: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  console.log(await this.getText("locator/xpath/css selector"));
  //output: Text of given selector
}

getAttribute

/**
 * @description: returns given attribute value of locator element.
 * @param {string}  locator - css selector/xpath of the element.
 * @param {string} attribute - html attribute to get value
 * @returns {string} - returns text string
 */
async getAttribute(locator: any, attribute: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  console.log(await this.getAttribute("locator/xpath/css selector", "class"));
  //output: returns locator class value
}

evaluateJS

// will be added in next versions.

isElementPresent

/**
 * @description: verifies given locator element is displayed or not.
 * @param {string}  locator - css selector/xpath of the element.
 * @returns {boolean} - returns true/false
 */
async isElementPresent(locator: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  console.log(await this.isElementPresent("locator/xpath/css selector"));
  //output: returns true if given locator is present in the dom
}

isElementEnabled

/**
 * @description: verifies given locator element is enabled or not.
 * @param {string}  locator - css selector/xpath of the element.
 * @returns {boolean} - returns true/false
 */
async isElementEnabled(locator: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  console.log(await this.isElementEnabled("locator/xpath/css selector"));
  //output: returns true if given locator is enabled in the dom
}

waitTillElementIsVisible

/**
 * @description: waits until locator element visibles.
 * @param {elementReference}  elementSelector - element reference.
 * @param {number} wait time
 * @returns {Promise<void>} - returns Promise of void
 */
async waitTillElementIsVisible(elementSelector: any, waitTime = 60000)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  await this.waitTillElementIsVisible("locator/xpath/css selector", 100000);
  //output: wait for given locator to be available in the dom
}

getInputBoxValue

/**
 * @description: returns value of inputbox.
 * @param {string}  locator - css selector/xpath of the element.
 * @returns {string} - returns text string
 */
async getInputBoxValue(locator: any)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  console.log(await this.getInputBoxValue("locator/xpath/css selector"));
  //output: returns inputbox value
}

downloadAFile

/**
 * @description: wait untill download process completes and save file with custom name.
 * @param {string}  locator - css selector/xpath of the element.
 * @param {string}  filePath - Complete path of the excel file, example: C:/resources/****.xlsx.
 * @returns {Promise<void>} - returns Promise of void
 */
async downloadAFile(downloadButton: String, filePath: string)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  const filePath = path.resolve(config.use.downloadsPath, downloadFileName);
  await this.downloadAFile(downloadButtonRef, filePath);
  //will wait for download completes and saves in to given filepath with custom name
}

uploadAFile

/**
 * @description: wait untill upload process completes and save file with custom name.
 * @param {string}  locator - css selector/xpath of the element.
 * @param {string}  filePath - Complete path of the excel file, example: C:/resources/****.xlsx.
 * @returns {Promise<void>} - returns Promise of void
 */
async uploadAFile(uploadButton: String, uploadFilePath: String)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  const filePath = path.resolve(config.use.downloadsPath, UploadFileName);
  await this.uploadAFile(UploadButtonRef, filePath);
  //will wait for upload completes
}

getElementRefByRole

/**
 * @description: will perform click action.
 * @param {string}  roleType - example: "alert"|"alertdialog"|"application"|"article"|"banner"|"blockquote"|"button"|"caption"|"cell"|"checkbox"|"code"|"columnheader"|"combobox"|"complementary"|"contentinfo"|"definition"|"deletion"|"dialog"|"directory"|"document"|"emphasis"|"feed"|"figure"|"form"|"generic"|"grid"|"gridcell"|"group"|"heading"|"img"|"insertion"|"link"|"list"|"listbox"|"listitem"|"log"|"main"|"marquee"|"math"|"meter"|"menu"|"menubar"|"menuitem"|"menuitemcheckbox"|"menuitemradio"|"navigation"|"none"|"note"|"option"|"paragraph"|"presentation"|"progressbar"|"radio"|"radiogroup"|"region"|"row"|"rowgroup"|"rowheader"|"scrollbar"|"search"|"searchbox"|"separator"|"slider"|"spinbutton"|"status"|"strong"|"subscript"|"superscript"|"switch"|"tab"|"table"|"tablist"|"tabpanel"|"term"|"textbox"|"time"|"timer"|"toolbar"|"tooltip"|"tree"|"treegrid"|"treeitem".
 * @param {string}  roleName - name of the element.
 * @returns {Promise<void>} - returns Promise of void
 */
async getElementRefByRole(roleType: string, roleName: string)

Usage:
import { UIHelper } from 'vita-playwright'
class UserClass extends UIHelper{
  await this.getElementRefByRole("link", "Dashboard");
  await this.getElementRefByRole("button", "Jobs");
  await this.getElementRefByRole("checkbox", "jobName");
}

Utilities

vita-playwright also provides utilities for Excel, Pdf, Date, Email and Lighthosue for perfomace.

Document Utilities

You can access rows and columns in order to change size, hide/show, or access cells within:

readData

/**
 * @description: it will take excel file path as input and will return excel Workbook object.
 * @param {string}  filePath - Complete path of the excel file, example: C:/resources/****.xlsx.
 * @returns {Promise<Workbook>} - returns Promise, if we resolves and will get Workbook object
 */
static async readData(filePath: string)

readDataFromExcelorCSV

/**
 * @description: it will take excel file path and sheetname as input and will return array of objects.
 * @param {string}  filePath - Complete path of the excel file, example: C:/resources/****.xlsx.
 * @param {string}  sheetname - name of the sheet name and it is optional. For CSV files no need pass this parameter.
 * @returns {Promise<Array<Object>>} - returns Promise, if we resolves and will get Array of Json objects. 
 * [{startDate: '****',endDate: '****', employeeId: '****',CompanyToken: '******'}]
 */
static async readDataFromExcelorCSV(filePath: string, sheetname: string)

filterData

/**
 * @description: it will filter excel data and will return filtered array of objects.
 * @param {string}  filePath - Complete path of the excel file, example: C:/resources/****.xlsx.
 * @param {string}  sheetname - name of the sheet name and it is optional. For CSV files no need pass this parameter.
 * @param {Object}  filterObject - {column Name:Row value} key:value pair. example: {startDate: '****'}  
 * @returns {Promise<Array<Object>>} - returns Promise, if we resolves and will get filtered Array of Json objects. 
 * [{startDate: '****',endDate: '****', employeeId: '****',CompanyToken: '******'}]
 */
static async filterData(filePath: string, sheetname: string)

updateExcelData

/**
 * @description: it will modify/update excel file based on input data.
 * @param {string}  filePath - Complete path of the excel file, example: C:/resources/****.xlsx.
 * @param {string}  sheetname - name of the sheet name and it is optional. For CSV files no need pass this parameter.
 * @param {Array<Object>}  exportData - excel modify data. example: [{startDate: '****',endDate: '****', employeeId: '****',CompanyToken: '******'}]
 * @returns {Promise<void>} - returns void promise. 
 */
static async updateExcelData(filePath: string, sheetname: string)

deleteAllFilesUnderDir

/**
 * @description: it will delete all files under given directory.
 * @param {string}  dirPath - Complete path of the directory which contain file, example: C:/resources.
 * @returns {Promise<void>} - returns void promise. 
 */
static async deleteAllFilesUnderDir(filePath: string, sheetname: string)

getPDFContents

/**
 * @description: it will take PDF file path as input and will return Json Object (Contains textual contents).
 * @param {string}  filePath - Complete path of the PDF file, example: C:/resources/****.pdf.
 * @returns { JSON<Object>} - returns JSON Object with 5 keys {content, metadata, info, pages & version} , each key contains different type of information related to that PDF.
 */
static async getPDFContents(pdfFilePath: string)

getDynamicJsonFileData

/**
 * @description: it will take JSON file path as input and will return Json Object (Contains JSON data). Use case would be when you want to load a file dynamically as typescript imports are static in nature.
 * @param {string}  filePath - Complete path of the JSON file, example: C:/resources/****.json.
 * @returns { JSON<Object>} - returns JSON Object from Json file 
 */
static async getDynamicJsonFileData(filePath: string)

replaceAllMatchesInJSONFile

/**
 * @description: it will take file path as input and will replace all the possible matches for specified string in given file.
 * @param {string}  filePath - Complete path of the JSON file, example: C:/resources/****.json.
 * @param {string}  stringToReplace - String to replace from file.
 * @param {string}  replacementValue - Replacement string value.
 * @returns  - {Promise<void>} - returns void promise. 
 */
static async replaceAllMatchesInJSONFile(filePath: string, stringToReplace: string, replacementValue: string)

filePathHandler

/**
 * @description: it will take file path as input and will replace all back slash '\' with forward slash '/'.
 * @param {string}  filePath - Complete path of the JSON file, example: C:/resources/****.json.
 * @returns {void} - returns void. 
 */
static filePathHandler(filePath:string)

countAllAssertions

/**
 * @description: it will take file path as input and will return count of all assertions in that file.
 * @param {string}  filePath - Complete path of the test script which contains assertions, example: C:/resources/****.json.
 * @returns {number} - returns count of total assertions. 
 */
static async countAllAssertions(filePath:string)

countAllFilesAssertions

/**
 * @description: it will take list of file paths as input and will return count of all assertions in all the files.
 * @param {string[]}  filePath - List of file paths of all the test scripts which contains assertions as an array of String.
 * @returns {number} - returns count of total assertions and prints total assertions for individual file with Name in console. 
 */
static async countAllFilesAssertions(filePath: string[])

Lighthouse Utilities

Lighthouse utilities are used to perform Lighthouse performace testing provided by Google.

auditLightHouse

/**
 * @description: it will take url of the web page and will calculates the performance of that web page and compare with given customThresholds. If any threashold doesn't meet the minimum value, then it test will be fail.
 * @param {string}  pageurl - url of the given page which needs to be calculated.
 * @param {string}  deviceType - type of device i.e desktop or mobile.
 * @param {string}  filename - to save the result the filename.
 * @param {object}  customThresholds - It is optional threshold object. example: {performance: 80,accessibility: 70,
'best-practices': 70,seo: 70, pwa: 70,} these are the default values.
 * @param {object}  format - This is optional. example: { html: true, csv:true, json: true}.
 * @returns {Promise<void>} - returns void promise. 
 */
static async auditLightHouse(pageurl: string, deviceType, filename, customThresholds = {
        performance: 80,
        accessibility: 70,
        'best-practices': 70,
        seo: 70,
        pwa: 70,
    }, format = { html: true })

//"Usage with new browser context:"
  test("light house testing "+vurl, async ({ page }) => {
    const browser = await playwright['chromium'].launch({
        args: ['--start-maximized', '--remote-debugging-port=9222'],
        channel:'chrome'
    });
    const context = await browser.newContext();
    const page = await context.newPage();
    page.goto(url);
    await LightHouseUtility.auditLightHouse(url, "desktop", url.split('/').join('_')+'.html');
  });

//"Usage with default playwright page:"
//Please set port in playwright.config.ts
args: ['--start-maximized','--remote-debugging-port=9222']

//calling auditLightHouse from test
 test("light house testing " + url, async ({ page }) => {
    page.goto(url);
    await LightHouseUtility.auditLightHouse(url, "desktop", url.split('/').join('_')+'.html');
});

createLightHouseReport

/**
 * @description: it creates new index.html file which has links to all pages htnl files.
 * @param {string}  dirPath - Complete path of the directory which contains Lighthouse performace html files, example: C:/lighthouse.
 * @param {String}  savefilepath - Based on files in directory, new index.html file will be created. To save that index.html file in given filepath. example: C:/lighthouse/complateReport/
 * @param {String} applicationName - Name of the Application
 * @returns {Promise<void>} - returns void promise. 
 */
static async createLightHouseReport(filePath: string, sheetname: string)

//Usage:
await LightHouseUtility.createLightHouseReport(process.cwd() + '/lighthouse/pages', process.cwd() + '/lighthouse/index.html', applicationName);

Date Utilities

Date related utilities

// will be added in next versions.

getDateInCustomFormat

/**
 * @description: returns date in required format.
 * @param {string}  date - date in the form of string, example: 01/01/2023.
 * @param {string}  format - format od date, example: DD/MM/YYYY.
 * @returns {string} - returns date in given format. 
 */
static getDateInCustomFormat(date:any, format: string)

getPastDateInCustomFormat

/**
 * @description: subtracts no of days|months|years|hours|minutes|seconds from given date.
 * @param {string}  date - date in the form of string, example: 01/01/2023.
 * @param {string}  format - format od date, example: DD/MM/YYYY.
 * @param {string}  durationType - example days, months, years, hours, minutes, seconds.
 * @param {string}  duration - no of days|months|years|hours|minutes|seconds.
 * @returns {string} - returns date in given format.
 */
static getPastDateInCustomFormat(date: any, format: string, durationType:DurationInputArg2, duration: DurationInputArg1)

getFutureDateInCustomFormat

/**
 * @description: adds no of days|months|years|hours|minutes|seconds from given date.
 * @param {string}  date - date in the form of string, example: 01/01/2023.
 * @param {string}  format - format od date, example: DD/MM/YYYY.
 * @param {string}  durationType - example days, months, years, hours, minutes, seconds.
 * @param {string}  duration - no of days|months|years|hours|minutes|seconds.
 * @returns {string} - returns date in given format.
 */
static getFutureDateInCustomFormat(date: any, format: string, durationType:DurationInputArg2, duration: DurationInputArg1)

getMinDateFromMultipleDates

/**
 * @description: return min date from given dates.
 * @param {Array<object<date,format>>}  datesArrayObject - array of dates in form of object example: [{date:10/01/2023, format: "DD/MM/YYYY"}, {date:20/01/2023, format: "DD/MM/YYYY"}].
 * @returns {string} - return min date amount given dates example: 10/01/2023.
 */
static getMinDateFromMultipleDates(datesArrayObject: any)

getMaxDateFromMultipleDates

/**
 * @description: return max date from given dates.
 * @param {Array<object<date,format>>}  datesArrayObject - array of dates in form of object example: [{date:10/01/2023, format: "DD/MM/YYYY"}, {date:20/01/2023, format: "DD/MM/YYYY"}].
 * @returns {string} - return max date amount given dates example: 20/01/2023.
 */

calculateRelativeDate

/**
 * @description: returns no of days "lessthan|Greaterthan" from given date.
 * @param {string}  fromDate - date in the form of string, example: 01/01/2023.
 * @param {string}  format - format od date, example: DD/MM/YYYY.
 * @returns {string} - returns string which is no of days "lessthan|Greaterthan" from given date. 
 */
static calculateRelativeDate(fromDate: any, format: string)

Database Utilities

Utilities related SQL server utilities

sqlDBConnection

/**
 * @description: establish the connection  with database.
 * @param {string}  configuration - example: {server: string, database: string, username:string, password: string, portNumber: number}.
 * @returns {Connection} - returns connection object. 
 */
static sqlDBConnection(fromDate: any, format: string)

executeSqlQuery

/**
 * @description: establish the connection  with database.
 * @param {string} connectionObj - connection object which will come from sqlDBConnection()
 * @param {string} queryString - query to execute
 * @returns {Connection} - returns connection object. 
 */
static async executeSqlQuery(connectionObj: any, queryString: any)

Data Comparisions

TODO: need to add Data Comparisions Utilities

// will be added in next versions

Missing Features

There are many features of playwright and other node modules needs to be added.

Readme

Keywords

none

Package Sidebar

Install

npm i vita-playwright

Weekly Downloads

108

Version

1.5.1-Beta-7-report-update-5

License

ISC

Unpacked Size

3.7 MB

Total Files

88

Last publish

Collaborators

  • trinadhdn
  • vemuladprasad
  • vijayvialto
  • hanumantha