How to resolve staleElementReferenceError: stale element reference: element is not attached to the page document in protractor?

How to resolve staleElementReferenceError: stale element reference: element is not attached to the page document in protractor?

我的应用有超过 1 个登录按钮,在测试各种功能时,它在 12 次迭代中的第 1 次和第 8 次迭代失败。需要建议来修复代码。

public async clickLoginMenu() {
    try {
        const button = await element(await by.buttonText('Login'));

           /* await browser.executeScript('return arguments[0].click()', await button).then(() => {
                browser.sleep(2000);
            });*/

            await browser.wait(until.presenceOf(await button), TIMEOUT_MILLIS,
                'Unable to locate logout button.');
            await button.click();
        } else {
            logger.info('Cannot find the login button to click');
        }
    } catch (e) {
        logger.error('Throw Exception error ' + e);
    }

}

您可以尝试在 presenceOf 和实际 click()

之间添加一个 elementToBeClickable 等待

所以:

  1. 等待出现
  2. 等待可点击
  3. 点击它

下面是我的工作代码:

public async clickLoginMenu() {
    try {
        const button = await element(await by.buttonText('Login'));
        if (await button.isDisplayed()) {
        await browser.wait(until.elementToBeClickable(await button), TIMEOUT_MILLIS,
                'Unable to locate logout button.');
        await button.click();
        } else {
            logger.info('Cannot find the login button to click');
        }
    } catch (e) {
        logger.error('Throw Exception error ' + e);
    }

}