我正在尝试根据早期断言的结果执行操作。我遇到以下情况,我想确定一个文档的版本数,它在下面的html中表示:
<ul data-testhook-id="accordion-body">
<li data-testhook-id="accordion-body-item">
<div>
<div data-testhook-id="version-1">
<div data-testhook-id="avatar">
<div data-id="tooltip">John Doe</div>
</div>
</div>
<span data-testhook-id="content">1. 17-08-2018 at 15:26</span>
</div>
<div data-testhook-id="version-2">
<div data-testhook-id="avatar">
<div data-id="tooltip">John Doe</div>
</div>
</div>
<span data-testhook-id="content">2. 20-08-2018 at 13:05</span>
</div>
<div data-testhook-id="version-3">
<div data-testhook-id="avatar">
<div data-id="tooltip">Jane Doe</div>
</div>
</div>
<span data-testhook-id="content">3. 20-08-2018 at 13:11</span>
</div>
<div data-testhook-id="version-4">
<div data-testhook-id="avatar">
<div data-id="tooltip">No Body</div>
</div>
</div>
<span data-testhook-id="content">4. 21-08-2018 at 13:11</span>
</div>
<svg width="12" height="12" data-testhook-id="icon-active-version"><path d="path-here"></path></svg>
</div>
</div>
</li>
每个测试ID为data-testhook-id="version-xxx"
的元素都是一行,其中包含版本信息以及我要计算的这些div元素。为此,我设置了以下内容:
cy.get('[data-testhook-id="accordion-body-item"] > div > div').its('length').as('versions')
现在,如果我添加以下断言,则可以顺利通过
cy.get('@versions').should('equal', 4)
但是,如果我尝试将发现的div数量的结果用作console.log中的变量,我将不再获得'4'而是[object,Object]。尝试过以下方法:
var size = cy.get('[data-testhook-id="asset-versions"] [data-testhook-id="accordion-body-item"] > div > div').its('length')
console.log('foo ' + size)
这导致foo [object Object]
被打印到控制台。
我想做的是使用选择器中的项目数来选择一个元素,例如:
cy.get('[data-testhook-id="accordion-body-item"] > div > div:nth-child(' + size + ')').find('svg').should('have.attr', 'data-testhook-id', 'icon-active-version')
但是由于var不是一个数字,所以我得到了味精
Error: Syntax error, unrecognized expression: :nth-child
[data-testhook-id="asset-versions"] [data-testhook-id="accordion-body-item"] > div > div:nth-child([object Object])
是否可以将找到的元素数量用作下一个选择器的变量?
答案 0 :(得分:2)
尝试一下:
cy.get('[data-testhook-id="accordion-body-item"] > div > div').its('length').then((size) => {
cy.get('[data-testhook-id="accordion-body-item"] > div > div:nth-child(' + size + ')').find('svg').should('have.attr', 'data-testhook-id', 'icon-active-version')
});
您不能分配或使用任何赛普拉斯命令的返回值。命令已排队并异步运行。命令真正返回的是Chainable<typeOfValueYouWant>
,换句话说,它是一种队列对象,可以按所需的值进行解析。
了解更多here
顺便说一句:我认为您应该考虑改变选择元素的方法。了解更多here。
对于那些正在使用Typescript的用户-我为tslint编写了插件,可以防止出现此错误:https://github.com/krzysztof-grzybek/tslint-plugin-cypress