Cypress - 別名


Cypress 別名是一個重要的元件,具有多種用途。這些用途列在下面:

共享上下文

我們必須使用 .as() 來為需要共享的內容設定別名。要為物件和基本型別設定別名,可以使用 Mocha 上下文物件。別名物件可以使用 this.* 訪問。

Mocha 預設情況下,為所有適用於測試的鉤子共享上下文,並且在測試執行後會重新整理別名屬性。

describe('element', () => {
   beforeEach(() => {
      cy.wrap('eleone').as('x')
   })
   context('subelement', () => {
      beforeEach(() => {
         cy.wrap('eletwo').as('y')
      })
         it('aliases properties', function () {
            expect(this.x).to.eq(' eleone ')
            expect(this.y).to.eq(' eleone ')
         })
      })
   })
})

我們可以透過共享上下文來處理 fixture。我們還可以使用 cy.get()(這是一個非同步命令)來使用 @ 符號訪問別名(而不是使用 this.*)。這是一個同步命令。

beforeEach(() => {
   // alias fixtures
   cy.fixture('users.json').as('u')
})
it('scenario', function () {
   // '@' to handle aliases
   cy.get('@u').then((u) => {
      // access element argument
      const i = u[0]
      //verification
      cy.get('header').should('contain', u.name)
   })
})

元素

別名可以與文件物件模型 (DOM) 元素一起使用,並在以後重複使用。在下面的示例中,Cypress 預設情況下會建立一個對作為 cols 別名獲得的 td 集合的引用。要使用相同的 cols,我們必須使用 cy.get() 命令。

// alias td in tr
cy.get('tr').find('td').as('cols')
cy.get('@cols').first().click()

由於我們在 cy.get() 中使用了 @,因此 Cypress 會搜尋當前的別名 (cols) 並返回其引用。

路由

別名可以與路由一起使用。它確保應用程式已發出請求。然後,它等待伺服器的響應並訪問請求以進行驗證。

cy.intercept('POST', '/users', { id: 54 }).as('u')
cy.get('#btn').click()
cy.wait('@u').then(({ request }) =>{
//assertion
   expect(request.body).to.have.property('name', 'User')
})
cy.contains('User added')

請求

別名可以與請求一起使用。我們可以為請求設定別名,並在以後使用其屬性。這可以透過以下方式完成:

cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
// other implementations if any
cy.get('@c').should((response) => {
   if (response.status === 404) {
      // assertion
         expect(response).to.have.property('duration')
      } else {
         // do something else
      }
   })
})
廣告

© . All rights reserved.