Webdriver JS - Store sendKeys to variable and reuse

788 Views Asked by At

Currently I have a form with 10 fields that I need to do sendkeys > store the value and after assert this value when save the form. For each of these fields I need to create a function and store the value in a variable or is there a better way?

My actual code:

var email = driver.findElement(By.name('email'));
email.sendKeys('[email protected]');
email.getAttribute("value").then(function(email_text) {
    var email = email_text;
});

Cheers, Rafael

2

There are 2 best solutions below

2
Sabik On

If I understand correct, the process looks like you should fill some fields, remember their values and check values after the form has been submitted.

There is no one standard decision for tasks like this, it depends on developer.

So, we know which values we need and can store it for example in map

{
'email':'[email protected]',
'telephone':111222333
}

Key is name for finding element, value - for sendKey and checkValue methods.

You should write two methods, which will work with test data map and will fill inputs and check values in cycle by map keys.

1
martin770 On

Do you mean you want to do this as an array?

// you can represent each field as an object
var fields = [
    { elementName: 'email',    expectedText: '[email protected]' },
    { elementName: 'password', expectedText: 'bla bla bla' }
];

// sendKeys to each field with the specified text
fields.forEach(function(field) {
    browser.driver.findElement(by.name(field.elementName)).sendKeys(field.expectedText);
});

// to get all the field text (from promises) and store it as an array
browser.controlFlow().execute(function() {
    var textArray = [];
    fields.forEach(function(field) {
        browser.driver.findElement(by.name(field.elementName)).getAttribute('value').then(function(actualText) {
            textArray.push({elementName: field.elementName, actualText: actualText});
        });
    });
    return textArray;
}).then(function(storedTextArray) {
    // do something with the stored text array here
});