什麼是 Cypress 別名?
Cypress 別名是一個重要的組成部分,有多種用途。它們如下所示 −
共享上下文
我們必須使用 .as() 為我們必須共享的內容設定別名。要為物件和基元設定別名,請使用 Mocha 上下文物件。可以使用 - this.* 訪問 aliased 物件。
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 ') }) }) }) })
我們可以透過共享上下文來處理固定裝置。我們還可以使用 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 } }) })
廣告