在 Appium 中切换上下文后无法 select WebView 元素

Unable to select WebView element after switching context in Appium

我 运行 在尝试测试 iOS 应用程序时遇到 webdriverio/appium 的奇怪问题。该应用程序有一个带有标记为 "Refresh" 的按钮的 WebView。当我尝试测试此按钮时,出现 "not displayed" 错误(请参阅下面的代码)。

it('should have the Refresh button', () => {
    WebViewScreen.waitForWebsiteLoaded();

    // Verify that Refresh button is displayed
    WebViewScreen.switchToContext(CONTEXT_REF.WEBVIEW);
    const button = $('button=Refresh');
    expect(button).toBeDisplayed();
    WebViewScreen.switchToContext(CONTEXT_REF.NATIVE);
});

请注意,我在测试按钮之前将上下文切换到 WEBVIEW。查看 Appium 日志,查找按钮 ($('button=Refresh')) 的请求返回 404。尝试了不同的选择器:['button[data-test="refresh-button"]'],但没有成功。我什至放了一个 browser.debug() 并在 REPL 中查询 - 仍然是 404 - 尽管我可以在屏幕上看到按钮!

我知道我的 webdriverio/appium 设置很好,因为完全相同的代码适用于另一个带有 WebView 和按钮的 iOS 屏幕 - 唯一的区别是按钮名称。

我还通过转到独立网页并测试该按钮排除了我的选择器不正确的可能性 - 在这种情况下没有错误!这是独立的网页代码 - 唯一的区别是没有上下文切换调用:

it('should have the Refresh button', () => {
    browser.url('https://example.site.com/');

    // Verify that Refresh button is displayed
    const button = $('button=Refresh')
    expect(button).toBeDisplayed();
});

关于如何调试它有什么想法吗?关于切换到 WEBVIEW 上下文是否有任何我遗漏的细微差别?

终于在这方面取得了突破 - 感谢 Alexi's suggestions on the Appium forum。事实证明,我的应用程序中有多个 WebView,我必须将上下文切换到正确的那个。诀窍是在 Appium 上设置 fullContextList 选项以获取有关可用上下文的更多信息,然后 select 正确的

切换到常规网络视图时会发生什么

public static void switch(AppiumDriver driver) {
    Set<String> contextNames = driver.getContextHandles();
    for (String context : contextNames) {
        log.debug("Context available:{}", context);
        if (StringUtils.startsWithIgnoreCase(context, "WEBVIEW")) {
            log.debug("Switch to WEBVIEW");
            driver.context(context);

        }