我正在尝试根据先前断言的结果执行一个操作。我有以下情况,我想确定文档的版本数,这在下面的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 div的元素都是一行包含版本信息的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不是一个数字,所以我得到msg
Error: Syntax error, unrecognized expression: :nth-child
[data-testhook-id="asset-versions"] [data-testhook-id="accordion-body-item"] > div > div:nth-child([object Object])是否可以将找到的元素数量用作下一个选择器的变量?
发布于 2018-08-21 15:37:06
试试这个:
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')
});您不能分配或使用任何Cypress命令的返回值。命令被排入队列并异步运行。命令真正返回的是Chainable<typeOfValueYouWant>,换句话说,它是一种队列对象,可以根据所需的值进行解析。阅读更多here
顺便说一句:我认为你应该考虑改变你选择元素的方法。阅读更多here。
对于那些正在使用Typescript的人-我为tslint写了一个插件,它可以防止犯这个错误:https://github.com/krzysztof-grzybek/tslint-plugin-cypress
https://stackoverflow.com/questions/51943474
复制相似问题