Cypress学习文档

沉淀cypress对常用html组件定位的文档


检查动态元素是否存在(条件判断)

<h1>1. 背景</h1> <p>Cypress.$('tr.dx-row-lines').length是同步的,在cypress启动的时候就已经加载了,所以很可能结果值是0; 那么对一些动态加载的元素,不能直接使用该语句进行判断,如该语句永远false: <code>if ($body.find('#service-catalog-publish_isOverwrite').length)</code> <strong>根本原因: </strong> 是DOM加载是同步的,Cypress的命令执行是异步的 <strong> 解释如下:</strong></p> <pre><code class="language-javascript">Cypress.$('tr.dx-row-lines').length is evaluated immediately because it is a sync method. so it's evaluating before other Cypress code is ran. I suggest reading the entirety of our Introduction to Cypress guide. Specifically the section on mixing async and sync code. Issues in our GitHub repo are reserved for potential bugs or feature requests. This issue will be closed since it appears to be neither a bug nor a feature request. We recommend questions relating to how to use Cypress be asked in our community chat. Also try searching our existing GitHub issues, reading through our documentation, or searching Stack Overflow for relevant answers.</code></pre> <h1>2. 解决</h1> <p>步骤1:进入该步骤时,先使用cy.get,阻塞在cypress的异步原子操作中,然后在该原子操作内部,进行DOM操作,定位该元素是否存在。 步骤2:原子操作内,判断存在时,进行下一步操作</p> <pre><code class="language-javascript">cy.get('body').then(($body) =&gt; { if ($body.find('div.ui-dialog-content.ui-widget-content &gt; p-messages &gt; div &gt; ul &gt; li:nth-child(2) &gt; span').length) { // element found, do something here... cy.get('div.ui-dialog-titlebar.ui-widget-header.ui-helper-clearfix &gt; a &gt; span') .click() } else { // do something else... } })</code></pre> <h1>3. Reference</h1> <p>[1]. <a href="https://github.com/cypress-io/cypress/issues/7172">作者对dom sync和cypress async解释</a></p>

页面列表

ITEM_HTML