前言
頁面上有些元素定位路徑比較復雜,可以先定位到該元素使用別名,通過這個別名去操作元素,這樣看起來簡潔一些。
.as()使用別名定位元素
table表格上的元素定位使用示例
<table class="as-table table table-bordered">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Row 1: Cell 1 <button class="btn btn-primary btn-success">Changed</button>
</td>
<td>
Row 1: Cell 2 <button class="btn btn-primary">Change</button>
</td>
</tr>
<tr>
<td>
Row 2: Cell 1 <button class="btn btn-primary">Change</button>
</td>
<td>
Row 2: Cell 2 <button class="btn btn-primary">Change</button>
</td>
</tr>
</tbody>
</table>
// The following DOM command chain is unwieldy.
// To avoid repeating it, let's use `.as()`!
cy.get('.as-table')
.find('tbody>tr').first()
.find('td').first()
.find('button').as('firstBtn')
// To reference the alias we created, we place an
// @ in front of its name
cy.get('@firstBtn').click()
cy.get('@firstBtn')
.should('have.class', 'btn-success')
.and('contain', 'Changed')
.as() 重新命名路由
當點頁面上某個按鈕,發網絡請求的時候,我們可以判斷它的reponse
當點上面按鈕后,發了個網絡請求,於是我們需要判斷這個請求是否請求成功,狀態碼反回200
// Alias the route to wait for its response
cy.server()
cy.route('GET', 'comments/*').as('getComment')
// we have code that gets a comment when
// the button is clicked in scripts.js
cy.get('.network-btn').click()
// https://on.cypress.io/wait
cy.wait('@getComment').its('status').should('eq', 200)
QQ交流群:939110556