Cypress에서 같은 테스트 코드 파일이여도 섹션을 나눌 수 있다.
describe("Home page", () => {
beforeEach(() => {
cy.visit("http://localhost:3000")
})
context("Hero section", () => { // context() 을 통해 섹션을 나눌 수 있다.
it("the h1 contains the correct text", () => {
cy.getByData("hero-heading").contains(
"Testing Next.js Applications with Cypress"
)
})
it("the features on the homepage are correct", () => {
cy.get("dt").eq(0).contains("4 Courses")
cy.get("dt").eq(1).contains("25+ Lessons")
cy.get("dt").eq(2).contains("Free and Open Source")
})
})
context("Courses section", () => {
it("Course: Testing Your First Next.js Application", () => {})
})
})
context() 를 통해 섹션을 나눌 수 있으며, 테스트 통과 결과를 통해서 볼 수 있다.
코드에서의 hero section이 있다. 이로서 섹션을 나눌 수 있다는걸 알았다.
예제 템플릿에서 Get started 버튼을 클릭하고 싶다.
Get started 버튼이 밑 블록의 mt-6 이지만 data 속성이 없어서 커스텀 명령을 사용할 수 없다.
data 속성이 있는 course-0은 위 컴포넌트들을 감싼 wrapper 이며, data속성을 추가해서 접근해도 되지만 현재로는 wrapper를 통해 접근해야 한다.
.find() 를 통해 DOM element에 접근할 수 있다.
context("Courses section", () => {
it("Course: Testing Your First Next.js Application", () => {
cy.getByData("course-0").find("a")
})
})
위 코드처럼 접근이 가능하다. mt-6 div안에 a태그가 존재한다.
테스트코드의 결과를 보면 4개의 요소가 찾아졌다는걸 볼 수 있다.
예제 템플릿의 APP INSTALL AND, INSTALLING, SETTING, Get started
이렇게 4개가 다 찾아진걸 볼 수 있다.
그럼 마지막 요소에 접근하고 클릭을 해보자.
cy.getByData("course-0").find("a").eq(3).click()
이렇게 data 속성에 없는 요소에 접근 방법을 알아보았다.
이 방법은 추천되는 방식이 아니다.
요소가 추가되거나 제거되면 순서가 꼬이게 되며, 마크업을 수정할 수 없는 상황일시에만 사용해야 한다.
요소를 클릭했고, 경로가 바뀌었다. 바뀐경로를 검증하는 테스트코드도 추가해보자.
location() 을 통해 window.location 에 접근할 수 있다.
cy.location("pathname").should("eq", "/testing-your-first-application") // 경로가 /testing-your ... 이랑 같은지 확인
예제의 다른 코스들이 2개 더 있고, 똑같이 테스트 코드를 적용해보자.
context("Courses section", () => {
it("Course: Testing Foundations", () => {
cy.getByData("course-1").find("a").eq(3).click() // data-set이 course-0인 요소에 접근하고 a element를 찾고 3번째 요소에 접근하고 클릭
cy.location("pathname").should("eq", "/testing-foundations") // 경로가 /testing-your ... 이랑 같은지 확인
})
})
context("Courses section", () => {
it("Course: Cypress Fundamentals", () => {
cy.getByData("course-2").find("a").eq(3).click() // data-set이 course-0인 요소에 접근하고 a element를 찾고 3번째 요소에 접근하고 클릭
cy.location("pathname").should("eq", "/cypress-fundamentals") // 경로가 /testing-your ... 이랑 같은지 확인
})
})