cypress 的错误消息 - the element has become detached from the dom

数字先锋
• 阅读 3157

这个错误消息的分析和解决方案,可以参考 Cypress 的官方文档

这个错误消息提示我们,我们编写的 Cypress 代码正在同一个“死去”的 DOM 元素交互。
cypress 的错误消息 - the element has become detached from the dom

显然,在真实的使用场景下,一个用户也无法同这种类型的 UI 元素交互。

看个实际例子:

<body>
  <div id="parent">
    <button>delete</button>
  </div>
</body>

这个 button 被点击之后,会将自己从 DOM 树中移除:

$('button').click(function () {
  // when the <button> is clicked
  // we remove the button from the DOM
  $(this).remove()
})

下列这行测试代码会引起错误:

cy.get('button').click().parent()

当 cypress 执行到下一个 parent 命令时,检测到施加该命令的 button 已经从 DOM 树中移除了,因此会报错。

解决方案:

cy.get('button').click()
cy.get('#parent')

解决此类问题的指导方针:

Guard Cypress from running commands until a specific condition is met

两种实现 guard 的方式:

  1. Writing an assertion
  2. Waiting on an XHR

看另一个例子:

输入 clem,从结果列表里选择 User clementine , 即所谓的 type head search 效果。

cypress 的错误消息 - the element has become detached from the dom

测试代码如下:

it('selects a value by typing and selecting', () => {
  // spy on the search XHR
  cy.server()
  cy.route('https://jsonplaceholder.cypress.io/users?term=clem&_type=query&q=clem').as('user_search')

  // first open the container, which makes the initial ajax call
  cy.get('#select2-user-container').click()

  // then type into the input element to trigger search, and wait for results
  cy.get('input[aria-controls="select2-user-results"]').type('clem{enter}')

  // select a value, again by retrying command
  // https://on.cypress.io/retry-ability
  cy.contains('.select2-results__option', 'Clementine Bauch').should('be.visible').click()
  // confirm Select2 widget renders the name
  cy.get('#select2-user-container').should('have.text', 'Clementine Bauch')
})

要点:

使用 cy.route 监控某个 XHR, 这里可以监控相对路径吗?

本地测试通过,在 CI 上运行时会遇到下列错误:

cypress 的错误消息 - the element has become detached from the dom

如何分析这个问题呢?可以使用 pause 操作,让 test runner 暂停。

// first open the container, which makes the initial ajax call
cy.get('#select2-user-container').click().pause()

当我们点击了 select2 widget 时,会立即触发一个 AJAX call. 而测试代码并不会等待 clem 搜索请求的返回。它只是一心查找 "Clementine Bauch" 的 DOM 元素。

// first open the container, which makes the initial ajax call
cy.get('#select2-user-container').click()

// then type into the input element to trigger search,
// and wait for results
cy.get('input[aria-controls="select2-user-results"]').type('clem{enter}')

cy.contains('.select2-results__option',
   'Clementine Bauch').should('be.visible').click()

上面的测试在本地运行时大部分时间可能会通过,但在 CI 上它可能会经常失败,因为网络调用速度较慢,浏览器 DOM 更新可能较慢。 以下是测试和应用程序如何进入导致 “detached element” 错误的竞争条件。

  1. 测试点击小部件
  2. Select2 小部件触发第一个搜索 Ajax 调用。 在 CI 上,此调用可能比预期慢。
  3. 测试代码输入“clem”进行搜索,这会触发第二个 AJAX 调用。
  4. Select2 小部件接收对带有十个用户名的第一个搜索 Ajax 调用的响应,其中一个是“Clementine Bauch”。 这些名称被添加到 DOM

然后测试搜索可见的选择“Clementine Bauch” - 并在初始用户列表中找到它。

然后,测试运行器将要单击找到的元素。注意这里的竟态条件。当第二个搜索 Ajax 调用“term=clem”从服务器返回时。 Select2 小部件删除当前的选项列表,只显示两个找到的用户:“Clementine Bauch”和“Clementina DuBuque”。

然后测试代码执行 Clem 元素的点击。

Cypress 抛出错误,因为它要单击的带有文本“Clementine Bauch”的 DOM 元素不再链接到 HTML 文档; 它已被应用程序从文档中删除,而 Cypress 仍然引用了该元素。

这就是问题的根源。

下面这段代码可以人为地让这个竟态条件总是触发:

cy.contains('.select2-results__option',
            'Clementine Bauch').should('be.visible')
  .pause()
  .then(($clem) => {
    // remove the element from the DOM using jQuery method
    $clem.remove()
    // pass the element to the click
    cy.wrap($clem)
  })
  .click()

既然了解了竟态条件触发的根源,修正起来就有方向了。

我们希望测试在继续之前始终等待应用程序完成其操作。

解决方案:

cy.get('#select2-user-container').click()

// flake solution: wait for the widget to load the initial set of users
cy.get('.select2-results__option').should('have.length.gt', 3)

// then type into the input element to trigger search
// also avoid typing "enter" as it "locks" the selection
cy.get('input[aria-controls="select2-user-results"]').type('clem')

我们通过 cy.get('XXX').should('') 操作,确保在执行 clem 输入之前,初始的 user list 对应的 AJAX 一定回复到服务器上了,否则 select2-options 的长度必定小于 3.

当测试在搜索框中键入“clem”时,应用程序将触发 Ajax 调用,该调用返回用户的子集。 因此,测试需要等待显示新集合 - 否则它将从初始列表中找到“Clementine Bauch”并遇到detached 错误。我们知道只有两个用户匹配“clem”,因此我们可以再次确认显示的用户数以等待应用程序。

/ then type into the input element to trigger search, and wait for results
cy.get('input[aria-controls="select2-user-results"]').type('clem')

// flake solution: wait for the search for "clem" to finish
cy.get('.select2-results__option').should('have.length', 2)

cy.contains('.select2-results__option', 'Clementine Bauch')
    .should('be.visible').click()

// confirm Select2 widget renders the name
cy.get('#select2-user-container')
  .should('have.text', 'Clementine Bauch')

如果盲目的在 click 调用里传入 force:true 的参数,可能会引入新的问题。

cypress 的错误消息 - the element has become detached from the dom
cypress 的错误消息 - the element has become detached from the dom

更多Jerry的原创文章,尽在:"汪子熙":
cypress 的错误消息 - the element has become detached from the dom

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这