赛普拉斯如何暂时逃离cy.within()
我正在努力在 cypress 上编写自动测试仪代码。由于 web 应用程序是 vue.js 项目,页面由 src 中的组件组成。因此,在 cypress 中,我决定将所有后续命令的范围限定在组件根目录内,而不是文档根目录 (html) 内。这样 cy.get 或 cy.find 将在组件根 dom 内查询。
但是我经常需要查询当前作用域组件之外的一些元素。例如:当我有自定义选择在组件外部呈现下拉列表时,在 cypress 中,在 cy.within 内部无法选择下拉选项,因为它是在组件根外部呈现的。
因此,我尝试暂时转义范围以选择下拉列表,然后再次返回范围以执行下一个命令。
cy.get(".account-mortgage-component form").within(() => {
cy.get("input[name='postcode']").type("ng2 6dg").blur();
// click input.select-address to open dropdown
cy.get("input.select-address").click();
// then dropdown is rendered outside .account-mortgage-component. so next command can not work
cy.get(".select-address-dropdown").contains("3 Carnarvon Road, West Bridgford").click();
// I hope to escape current scope, so make above code to work. after this I should come back to scope again for next commands.
cy.root().submit();
});
<div>
<form>
<input name="postcode" />
<div>
<input />
</div>
</form>
<div>
<div>
<ul>
<li>3 Carnarvon Road, West Bridgford</li>
<li>5 Carnarvon Road, West Bridgford</li>
<li>6 Carnarvon Road, West Bridgford</li>
</ul>
</div>
回答
cy.document().its('body')会给你一个在 之外的主题,.within()它似乎在之后(仍在回调中)回到内部范围。
cy.get('body').find('div.without'); // checking this query first (outer scope)
cy.get('div.myform').within(() => {
cy.contains('text within'); // inner scope
cy.document().its('body').find('div.without'); // outer scope
cy.contains('text within'); // inner scope
})
用这个 html 测试
<body>
<div class="myform">
<div>text within</div>
</div>
<div class="without">text without</div>
</body>
嵌套内部
您可以.within()使用相同的突破模式嵌套语句,
cy.get('div.scope1')
.within(() => {
cy.contains('text within scope1'); // testing in scope1
cy.document().its('body').find('div.scope2')
.within(() => {
cy.contains('text within scope2'); // switch to scope2
})
cy.contains('text within scope1'); // back to scope1
})
用这个 html 测试
<body>
<div class="scope1">
<div>text within scope1</div>
</div>
<div class="scope2">
<div>text within scope2</div>
</div>
</body>