네트워크 요청 및 응답을 조작하고 테스트 해보자.
.intercept() 를 기본적인 사용법은 아래와 같다.
cy.intercept("POST", "/users")
/users 경로에 대한 모든 POST요청을 가로챈다.
요청에 대한 대기같은 추가작업을 위해 대체로 별칭을 부여한다.
cy.intercept("POST", "/users").as("signup")
// ...
cy.wait("@signup")
응답데이터를 mock 하기 위해 재정의 해야할 때 사용한다.
우선 아래와 같이 요청을 가로채고 별칭을 달아준다.
beforeEach(() => {
// ...
cy.intercept("GET", "/transactions/public*").as("publicTransactions")
// ...
})
그 후 모킹하기 위해 재정의 해버린다.
cy.intercept("GET", "/transactions/public*", {
// ...
fixture: "public-transactions.json",
}).as("mockedPublicTransactions")
/transactions/public* 과 일치한 모든 요청을 가로채고 모의 데이터(json) 을 제공한다. 우리고 이 가로챈 intercept를 mockedPublicTransactions 라고 별칭을 부여한다.
헤더도 편집할 수 있다.(기존 헤더에 추가되는 방식)
cy.intercept("GET", "/transactions/public*", {
headers: {
"X-Powered-By": "Express",
Date: new Date().toString(),
},
})
cy.intercept("POST", "/bankaccounts", (req) => {
const { body } = req
req.continue((res) => {
res.body.data.listBankAccount = []
})
})
응답 데이터를 수정할 수 있다. 이때 .continue() 를 사용한다.
이때 Interception lifecycle 관련된 이야기가 나오는거 같은데, 다음에 알아보도록 하자.
예시로 요청의 쿼리를 가로채고 쿼리 검사를 한 후 속성을 추가하는 코드이다. 이와 같은 방식으로 요처도 먼저 가로챌 수 있다.
cy.intercept("POST", apiGraphQL, (req) => {
const { body } = req
if (
body.hasOwnProperty("operationName") &&
body.operationName === "CreateBankAccount"
) {
req.alias = "gqlCreateBankAccountMutation"
}
})
부가적인 참고 문서