首页 > 解决方案 > Selenium (python) 测试 React-js 前端在尝试将文本输入到输入字段时导致过时的错误消息

问题描述

我对我的问题有一个模糊的概念,但不知道如何在 Selenium 中克服它。React-js 前端更新输入字段中文本输入的每个字符的 DOM,因此 Selenium 看到 DOM 已更改,因此我的变量引用不再指向正确的 DOM 元素,因此是陈旧的,即使重新加载DOM,该元素实际上仍然存在,所以我得到以下信息:

Message: The element reference of <input class="input-1" name="firstname" type=""> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed

我的测试中的示例行如下所示:

def test_fill_in_name_and_submit_with_enter(self):
    firstname_input = self.browser.find_element_by_name('firstname')
    firstname_input.send_keys('Adam')
    firstname_input.send_keys(Keys.ENTER)

输入第一个字符,然后测试失败并显示前面的消息。Stackoverflow 中有一些答案,但它们对我来说毫无意义,代码似乎很复杂并且特定于用例,而上面的代码非常通用和简单,所以也许我们可以得到一个简单的答案来解决必须变得非常常见的问题这几天发。

标签: pythonreactjsselenium

解决方案


好吧,不要这样做。这是我的 JS 代码的一个问题,它导致了我在重建代码后自己尝试复制的问题。如果我尝试输入它会取消选择输入框,因为我正在做一些奇怪的箭头功能。我恢复为静态输入,之后这很好,并且使用 send_keys 进行测试按预期工作。


好的,所以最后我以一种看起来很可怕和 hacky 的方式完成了这项工作,但这可能只是因为我的 React-js 应用程序设置了一个 onChange ,它将状态值设置为等于输入字段数据:

from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.by import By

def enter_text_into_input_fields(browser, text, field_name):
    for l in text:
        browser.find_element(By.NAME, field_name).send_keys(l)

class SomeBasicTest(StaticLiveServerTestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()
        self.browser.get(f'{self.live_server_url}/')

    def tearDown(self):
        self.browser.quit()

    def test_fill_in_name_and_submit_with_enter(self):
        enter_text_into_input_fields(self.browser, 'Adam', 'firstname')
        self.browser.find_element_by_name('firstname').send_keys(Keys.ENTER)

        app_title = self.browser.find_element_by_css_selector('html body div#app.app h1').text
        self.assertIn('This is our app title', app_title)


推荐阅读