使用webdriverio从React包装的span获取文本

时间:2016-07-22 17:34:08

标签: javascript reactjs mocha webdriver-io

我正在为React前端应用程序编写测试。 其中一个测试必须检查服务器返回值的方式。 也就是说,我有以下跨度:

<span id='result'>
    <!-- our version of react wraps the resulting text by default -->
    <span data-reactid>the actual result</span>
</span>


// test.js   
getResult() {
    let a = browser.getText('#result span');
    console.log('a:', a);
}  // unfortunately, getting it this way will mean having to rewrite the test once we upgrade to a newer version of React (after 15 is does not do the wrapping anymore)

所以,基本上..我怎样才能得到文本值,使得react生成的span具有id或class ...或者dom结构的更改不会意味着必须的任何其他方式重写测试?

1 个答案:

答案 0 :(得分:1)

我不确定如何只使用webDriver API,但您可以使用一些javascript来获取值。像这样:

var id = 'result';

client.execute(function(a) {
    return document.getElementById(a).textContent;
}, id).then(function(ret) {
     console.log(ret.value); // outputs: the actual result
});

通过使用textContent,即使您的选择器以父级跨度为目标,它也会在输出文本时忽略子级<span>标记。