Cypress (6) alias, sharing context 와 wait

SUNG JUN LEE·2023년 1월 3일
0

Cypress

목록 보기
6/11

공부를 하다보면 alias는 참 익숙한 용어이다.
여기서도 동일하게 사용된다.

alias

alias docs

문서에서는 element, request, intercepts 를 참조한다. 라고 명시되어 있다.

이게 위에 것들의 별칭을 부여하여 액세스할 수 있다고 한다.

// Create an alias using the `as()` Cypress Command
cy.get("table").find("tr").as("rows")
// Reference Cypress Alias `rows`
cy.get("@rows")

.get() 에서 별칭에 접근하려면 @ 를 사용하여 접근한다.

sharing context

Mocha의 공유 컨텍스트 개체를 활용하며, context를 자동으로 공유한다. 공유하고 싶은 항목을 .as() 를 사용하여 공유할 수 있다.

이러한 별칭과 속성은 테스트가 끝나면 자동으로 정리된다.

beforeEach(() => {
  // alias the $btn.text() as 'text'
  cy.get('button').invoke('text').as('text')
})

it('has access to text', function () {
  this.text // is now available
})

this.* 로 접근이 가능하다.

아래 방식으로도 가능하다.

describe('parent', () => {
  beforeEach(() => {
    cy.wrap('one').as('a')
  })

  context('child', () => {
    beforeEach(() => {
      cy.wrap('two').as('b')
    })

    describe('grandchild', () => {
      beforeEach(() => {
        cy.wrap('three').as('c')
      })

      it('can access all aliases as properties', function () {
        expect(this.a).to.eq('one') // true
        expect(this.b).to.eq('two') // true
        expect(this.c).to.eq('three') // true
      })
    })
  })
})

여기서 중요한점은 arrow function일때는 this.*를 사용하지 말라는 것

beforeEach(() => {
  // alias the users fixtures
  cy.fixture('users.json').as('users')
})

it('utilize users in some way', function () {
  // use the special '@' syntax to access aliases
  // which avoids the use of 'this'
  cy.get('@users').then((users) => {
    // access the users argument
    const user = users[0]

    // make sure the header contains the first
    // user's name
    cy.get('header').should('contain', user.name)
  })
})

arrow function일 경우 위 방식으로 주로 사용하면 될거라고 생각된다.

여기서 this.* 와 get 방식의 차이를 정리해보자면,

  1. arrow function 일 경우 this.* 사용불가
  2. this 방식은 처음 평가될때 컨텍스트에 저장되며, get 방식은 별칭에 액세스할때마다 값이 재평가된다고 한다. => 초기값만 바라보느냐, 매 액세스시 최신값을 바라보느냐 이 차이라고 생각된다.

2번이 무슨 뜻일까? 예시 코드를 보자.

const favorites = { color: 'blue' }

cy.wrap(favorites).its('color').as('favoriteColor')

cy.then(function () {
  favorites.color = 'red'
})

cy.get('@favoriteColor').then(function (aliasValue) {
  expect(aliasColor).to.eql('red')

  expect(this.color).to.eql('blue')
})

대략 이런 느낌?! 이다.

컨텍스트 공유의 가장 일반적인 사례가 cy.fixture() 를 처리할때 라고 하는데 이때는 비동기, this, arrow function 등 서술해야 하는 부분이 많으므로 이건 나중에 알아보자.

wait

테스트 코드를 쭉 진행하면서 특정 네트워크 요청의 완료까지 기다릴 수 있다.
이런 wait을 처리하기에 가장 좋은 방법은 alias를 기다리는 것이다.
element, intercept, request 등 별칭을 지정할 수 있는 모든 항목에 적용이 가능하다.

describe("User Sign-up and Login", () => {
  beforeEach(() => {
    cy.request("POST", "/users").as("signup") // creating the signup alias
  })

  it("should allow a visitor to sign-up, login, and logout", () => {
    cy.visit("/")
    // ...

    cy.wait("@signup") // waiting upon the signup alias

    // ...
  })
})

추후 참고 문서
Retry-ability

profile
FE developer

0개의 댓글