tm-playwright-framework
Version:
Playwright Cucumber TS framework - The easiest way to learn
197 lines (196 loc) • 8.79 kB
JavaScript
/**
* FILES.TS
*
* This TypeScript file contains methods to handle file management operations.
*
* @author Sasitharan, Govindharam
* @reviewer Sahoo, AshokKumar
* @version 1.0 - 1st-JUNE-2025
*
* @methods
* - `uploadFile`: Accepts an element locator as a `string` or Element and uploads a file from the given absolute or relative path.
* - `uploadMultipleFiles`: Accepts an element locator as a `string` or Element and uploads selected files from the given absolute or relative path.
* - `uploadFileByRelativePath`: Accepts an element locator as a `string` or Element and uploads a file from the given relative path.
* - `uploadMultipleFilesByRelativePath`: Accepts an element locator as a `string` or Element and uploads selected files from the given relative path.
*/
import { fixture } from "tm-playwright-framework/dist/hooks/pageFixture.js";
import Logger from 'tm-playwright-framework/dist/report/logger.js';
import path from 'path';
import fs from "fs-extra";
export default class FileUploadActions {
/* Method to be executed when an Object instantiated for this class */
constructor() { }
/**
* Accepts an element locator as a `string` or Element and uploads a file from the given absolute or relative path.
* @param {any} locator - The locator string or Element to identify the input field.
* @param {string} filePath - The absolute path or relative file path of the file to upload.
* @param {number} [timeOut=30000] - Optional timeout in milliseconds.
* @returns {Promise<void>} - Resolves when the file is uploaded.
*/
async uploadFile(locator, filePath, timeOut = Number(process.env.DEFAULT_TIMEOUT) ?? 30000) {
const timestamp = new Date().toISOString();
//const core = CoreFramework.getInstance();
let status = 'Success';
let message = '';
let obj;
try {
obj = typeof locator === 'object' ? locator : await fixture.page.locator(locator);
let resolvedPath = resolvePath(filePath);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`File not found: ${resolvedPath}`);
}
await obj.setInputFiles(resolvedPath);
message = `File upload action has been performed successfully. Path: ${filePath} `;
}
catch (error) {
status = 'Failed';
if (error instanceof Error) {
message = error.message;
}
else {
message = "An unknown error occurred during file upload";
}
}
finally {
Logger.logStatus(status, message);
}
await fixture.page.waitForLoadState("domcontentloaded", { timeout: timeOut });
return;
}
/**
* Accepts an element locator as a `string` or Element and uploads selected files from the given absolute or relative path.
* @param {string} locator - The locator string or Element to identify the input field.
* @param {string[]} filePath - An array of absolute paths of the files to upload.
* @param {number} [timeOut=30000] - Optional timeout in milliseconds.
* @returns {Promise<void>} - Resolves when the files are uploaded.
*/
async uploadMultipleFiles(locator, filePath, timeOut = Number(process.env.DEFAULT_TIMEOUT) ?? 30000) {
const timestamp = new Date().toISOString();
let status = 'Success';
let message = '';
let obj;
try {
obj = typeof locator === 'object' ? locator : await fixture.page.locator(locator);
const resolvedPaths = filePath.map(fp => {
return resolvePath(fp);
});
for (const file of resolvedPaths) {
if (!fs.existsSync(file)) {
throw new Error(`File not found: ${file}`);
}
}
await obj.setInputFiles(resolvedPaths);
message = `File upload action performed successfully. Paths: ${resolvedPaths.join(', ')}`;
}
catch (error) {
status = 'Failed';
if (error instanceof Error) {
message = error.message;
Logger.logSoftAssertFailure(error);
}
else {
message = "An unknown error occurred during file upload";
Logger.logSoftAssertFailure(error);
}
}
finally {
Logger.logStatus(status, message);
}
await fixture.page.waitForLoadState("domcontentloaded", { timeout: timeOut });
return;
}
/**
* Accepts an element locator as a `string` or Element and uploads a file from the given relative path.
* @param {string} locator - The locator string or Element to identify the input field.
* @param {string} filePath - The relative path of the file to upload.
* @param {number} [timeOut=30000] - Optional timeout in milliseconds.
* @returns {Promise<void>} - Resolves when the file is uploaded.
*/
async uploadFileByRelativePath(locator, filePath, timeOut = Number(process.env.DEFAULT_TIMEOUT) ?? 30000) {
const timestamp = new Date().toISOString();
let status = 'Success';
let message = '';
let obj;
try {
obj = typeof locator === 'object' ? locator : await fixture.page.locator(locator);
const objFile = await fixture.page.locator(locator);
if (!fs.existsSync(path.join(process.cwd(), filePath))) {
throw new Error(`File not found: ${path.join(process.cwd(), filePath)}`);
}
await objFile.setInputFiles(path.join(process.cwd(), filePath));
message = `File upload action has been performed successfully. Path: ${filePath}`;
}
catch (error) {
status = 'Failed';
if (error instanceof Error) {
message = error.message;
Logger.logSoftAssertFailure(error);
}
else {
message = "An unknown error occurred during file upload";
Logger.logSoftAssertFailure(error);
}
}
finally {
Logger.logStatus(status, message);
}
await fixture.page.waitForLoadState("domcontentloaded", { timeout: timeOut });
return;
}
/**
* Accepts an element locator as a `string` or Element and uploads selected files from the given relative path.
* @param {string} locator - The locator string or Element to identify the input field.
* @param {string[]} filePath - An array of relative paths of the files to upload.
* @param {number} [timeOut=30000] - Optional timeout in milliseconds.
* @returns {Promise<void>} - Resolves when the files are uploaded.
*/
async uploadMultipleFilesByRelativePath(locator, filePath, timeOut = Number(process.env.DEFAULT_TIMEOUT) ?? 30000) {
const timestamp = new Date().toISOString();
let status = 'Success';
let message = '';
let obj;
try {
obj = typeof locator === 'object' ? locator : await fixture.page.locator(locator);
const fullPaths = filePath.map(file => path.join(process.cwd(), file));
const resolvedPaths = fullPaths.map(fp => {
return resolvePath(fp);
});
for (const file of resolvedPaths) {
if (!fs.existsSync(file)) {
throw new Error(`File not found: ${file}`);
}
}
await fixture.page.locator(locator).setInputFiles(fullPaths);
message = `Multiple File upload action has been performed successfully. Path: ${filePath.toString()}`;
}
catch (error) {
status = 'Failed';
if (error instanceof Error) {
message = error.message;
Logger.logSoftAssertFailure(error);
}
else {
message = "An unknown error occurred during file upload";
Logger.logSoftAssertFailure(error);
}
}
finally {
Logger.logStatus(status, message);
}
await fixture.page.waitForLoadState("domcontentloaded", { timeout: timeOut });
return;
}
}
function resolvePath(filePath) {
if (filePath.startsWith('.'))
return path.join(process.cwd(), filePath);
if (filePath.toLowerCase().includes('{user.dir}'))
return filePath.toLowerCase().replace('{user.dir}', process.cwd());
if (!fs.existsSync(filePath)) {
filePath = path.join(process.cwd(), filePath);
}
if (!fs.existsSync(filePath)) {
throw new Error(`File not found: ${filePath}`);
}
return filePath;
}