是否有内置方法来等待元素匹配某些文本?

Is there a built-in method to wait for an element to match some text?

我们通常通过转到某个页面来测试我们的 SPA,执行保存值的操作,然后检查是否正在显示新值。由于所有内容都是异步更新的,这意味着新值可能需要一些时间才能出现。因此,要么之前的值会保留一段时间,要么我们正在检查文本的元素可能还不存在。

这是迄今为止我们每次想做的事情 "check that eventually an element with this selector contains this text":

// we need to wait for the text, because the result is async updated
// - the previous result might linger around for some time, or 
// the element might not even exist, failing the `getText()` call

const selector = '.feed-item div:nth-child(2) div:nth-child(2)';
browser.waitForText(selector);
browser.waitUntil(() => browser.getText(selector) === 'Temp: 20');

这行得通,但它有点像样板,不包含它感觉很奇怪,因为在所有客户端呈现的应用程序中这似乎是一件很自然的事情。

是否有更好的模式来执行此操作,使用 WebDriver.io,最好一次性完成?我尝试过的所有 1 行变体要么断言错误的元素,要么由于找不到元素而失败(因为结果尚未到来)。

您可以尝试两件事:

添加a custom command:

browser.addCommand('waitForContent', function (selector, text) {
    browser.waitForText(selector);
    browser.waitUntil(() => browser.getText(selector) === text);
})

browser.waitForContent('.feed-item div:nth-child(2) div:nth-child(2)', 'Temp: 20')

使用a text-based selector:

browser.waitForExist('.feed-item div:nth-child(2) div:nth-child(2)*=Temp: 20')

这个特定的选择器可能不起作用,因为我没有在其中有子选择器时对其进行测试。

I've got videos covering both 如果您有兴趣了解更多详情。