javascriptprotractorcucumberchaichai-as-promised

Is there a way to pass locator "by" as a string on protractor?


I'm trying to avoid using a switch-case to verify the locator and then creating an element.

This is how my code looks like:

    switch (name.by) {
        case "class":
            return element(by.className(name.value));
        case "cssselector":
            return element(by.cssSelector(name.value));
        case "id":
            return element(by.id(name.value));
        case "linktext":
            return element(by.linkText(name.value));
        case "name":
            return element(by.name(name.value));
        case "partiallinktext":
            return element(by.partialLinkText(name.value));
        case "tagname":
            return element(by.tagName(name.value));;
        case "xpath":
            return element(by.xpath(name.value));;
        default:
            throw new Error ('Invalid option.');
    }

It receives as a param a json structure like this:

"rangeFrom": {
   "by": "id",
   "value": "txtRentFrom"
},

I'm looking for something like:

element(by[name.by](name.value));

Does anyone know if there's a way to avoid using switch-case?


Solution

  • const dict = {
    "class": by.classname,
    "cssselector": by.cssSelector
    ...
    }
    
    return element(dict[name.by](name.value));