Functions.psm1

<#
.SYNOPSIS
    This function returns the JS code snippet for declaring a function to log a URL named logUrl.
#>

function Get-LogUrlFunctionDeclarationCode {
    return @"
// Logs a comment and a url
function logUrl(comment, urlString) {
    const url = new URL(urlString);
    console.log('%s: %s', comment, url.toString());
}
 
"@

}

<#
.SYNOPSIS
    This function return the JS code snippet for declaring a function that sets the text value of a control with selector.
#>

function Get-SetControlSelectorTextValueFunctionDeclarationCode {
    return @"
// Sets the value of a control
async function setControlSelectorTextValue(page, controlSelector, controlValue) {
    // Click the control, wait a bit, and then set the control value
    console.log(util.format('Setting control with selector %s to: %s', controlSelector, controlValue));
    const newControlValue = await page.evaluate((selector, value) => {
        // Return new value of the control
        document.querySelector(selector).value = value;
        return document.querySelector(selector).value;
    }, controlSelector, controlValue);
    console.log(util.format('Control with selector %s has been set to: %s', controlSelector, controlValue));
 
    // Make sure that the value was set correctly
    if (newControlValue !== controlValue) {
        throw new Error('Control value does match expected.');
    }
}
 
"@

}

<#
.SYNOPSIS
    This function returns the JS code snippet for declaring a function that waits for a specified amount of time.
#>

function Get-DelayFunctionDeclarationCode {
    return @"
// Waits specified timeout
function delay(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}
 
"@

}

<#
.SYNOPSIS
    This function returns the JS code snippet for opening a new async function declaration.
#>

function Get-AsyncFunctionDeclarationOpeningCode {
    param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$functionName
    )
    return "async function $($functionName)() {"
}