如何从json获取动态路径?

时间:2017-03-09 17:05:23

标签: javascript json selenium selenium-webdriver protractor

我正在尝试创建一个测试,我正在检查页面中是否存在所有必需元素。我有一个名为json.data的json文件,右边的noe看起来像这样:

    {
    "perfTest": {
        "input":"abc",
        "outputs":["a","b","c"],
        "elemAndXpath": ["Login","password","submit"]
        }
    }
}

我的测试是这样的:

    it("should check that required elements are present", function() {
        var elemNames = data.perfTest.elemAndXpath);
        elemNames.forEach(function(elemName){
            //search on the page that the specified elem is present
            expect(element(by.xpath("//div[.='" + elemName + "']")).isPresent()).toBe(true);
        });
    });

现在,如果可以找到路径相似的所有定位器,则此方法有效。我需要进行此测试才能从json文件中获取要使用的定位器路径。所以,我现在的JSON文件如下所示:

 {
    "perfTest": {
        "input":"abc",
        "outputs":["a","b","c"],
        "elemAndXpath": {
            "Login":"by.id('login')",
            "password":"by.id('pass')",
            "submit":"by.xpath(//button)"
        }
    }
}

我无法为此json文件编写测试。问题是由于最后一个键的动态特性。请帮帮我。

1 个答案:

答案 0 :(得分:1)

我认为您的问题是您将字符串传递给元素。试试这个:

var data = {
  "perfTest": {
    "input":"abc",
    "outputs":["a","b","c"],
    "elemAndXpath": {
      "Login":"by.id('login')",
      "password":"by.id('pass')",
      "submit":"by.xpath(//button)"
    }
  }
}

for(key in data.perfTest.elemAndXpath){
  expect(element(eval(data.perfTest.elemAndXpath[key]))).isPresent()).toBe(true)
}