Intercepting requests
요청에 대해 mocked response를 보내기 위해, 우선 요청을 가로채야한다.
MSW에서는, 요청 인터셉션을 request handler로 불리는 함수로 수행한다
// Intercept an HTTP GET request which path
// matches the "predicate", and resolve it
// using the given "resolver" function.
http.get(predicate, resolver)
"predicate"와 일치하는 경로의 HTTP GET 요청을 가로채고, 이를 주어진 "resolver" 함수를 사용하여 resolve한다
HTTP request
HTTP 요청은 http request 네임스페이스를 사용하여 가로챌 수 있습니다.
이 네임스페이스의 메서드들은 HTTP 메서드를 나타내며 (http.get(), http.post() 등),
파라미터를 두개 갖는다.
- predicate (string | RegExp)
- 요청 경로에 대한 문
- resolver (Response resolver)
- 가로챈 요청을 어떻게 다룰지 결정하는 함수
GET /pets 에 대한 예시
import { http, HttpResponse } from 'msw'
http.get(
'/pets',
({ request, params, cookies }) => {
return HttpResponse.json(['Tom','Jerry','Spike'])
}
}
- ‘/pets’ 문자열 : path predicate (경로 조건문)
- 해당 문자열과 경로가 일치하는 GET요청이 가로채질 것이다.
- resolver 함수 : 가로챈 요청의 정보를 받아서 어떻게 처리할지 결정한다
HTTP request matching
predicate 인자의 특성은 여러 기준으로 HTTP 요청을 가로챌 수 있게 해줌
Request pathname
predicate 인자가 문자열일때, 문자열과 일치하는 pathname의 요청이 가로채질 것이다.
상대 경로, 절대 경로 둘 다 작동한다.
export const handlers = [
http.get('/pets', petsResolver),
http.post('https://api.github.com/repo', repoResolver),
]
- 동시에 여러 요청을 가로채기 위해 요청 predicate 문자열에 특수 토큰을 포함시킬 수 있다.
- 가장 일반적인 토큰 중에 하나는 와일드 카드 (*)로, 그 위치에 있는 모든 문자열과 일치된다
// Intercept all GET requests to "/user":
// - GET /user
// - GET /user/abc-123
// - GET /user/abc-123/settings
http.get('/user/*', userResolver)
요청 경로명을 제공할 때, 반드시 어떤 쿼리 매개변수를 제외하도록 해야함
쿼리 매개변수는 리소스 식별에 영향을 미치지 않고 대신 서버로 추가 정보를 전송하는 수단으로 사용
MSW가 쿼리 매개변수를 감지하면 이를 제거하고 제거해야 한다는 경고를 출력
그러나 쿼리 매개변수의 값은 응답 resolver의 request.url 속성에서 사용 가능
정규 표현식
제공된 표현식과 일치하는 url을 가지는 요청을 가로챈다.
정규표현식의 동적인 특성을 활용하여 더 고급적인 요청 일치 시나리오를 처리할 수 있습니다.
// Intercept DELETE requests matching the regular expression.
// - DELETE /settings/sessions
// - DELETE /settings/messages
http.delete(/\/settings\/(sessions|messages)/, resolver)
Mocking responses
MSW는 fetch api 사양을 준수한다
즉, 내가 구성한 응답은 mocked response는 fetch 호출할 때 내가 받을 응답과 동일하다
가로챈 요청에 응답하려면 일치하는 요청 핸들러에서 유효한 Response 인스턴스를 반환하면 된다.
import { http } from 'msw'
export const handlers = [
http.get('/resource', () => {
return new Response('Hello world')
}),
]
현대 Node.js 버전과 브라우저에선 Response 클래스를 부를 필요는 없다
라이브러리는 Response instance의 다양한 형태를 지원한다
- Response.json(), Response.error() 같은 메서드로 생성된 간편한 응답도 지원한다.
Using HttpResponse class
일반적인 Fetch API 응답을 사용할 수 있을지라도, MSW에서 제공하는 HttpResponse 클래스를 사용하는 걸 추천한다.
native Response 보다 HttpResponse를 선호하는 두가지 이유
- HttpResponse 클래스는 유용하고 간단한 메서드들을 내장하고 잇다
- HttpResponse.json()
- HttpResponse.xml()
- HttpResponse.formData() 등등
- HttpResponse 클래스는 가로챈 응답에 대한 Set-Cookie 헤더를 설정하여 응답 쿠키를 모의로 설정할 수 있도록 지원합니다.
// 1. Import the "HttpResponse" class from the library.
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/resource', () => {
// 2. Return a mocked "Response" instance from the handler.
return HttpResponse.text('Hello world!')
}),
]
상태코드와 상태 텍스트 Mocking
응답 초기화 객체에 status와 statusText 프로퍼티를 제공하여 응답 상태와 상태코드를 구체화할수 있다
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/apples', () => {
return new HttpResponse(null, {
status: 404,
statusText: 'Out Of Apples',
})
}),
]
헤더 Mocking
응답 초기화 객체에 헤더 프로퍼티를 제공해서 응답 헤더를 구체화시킬 수 있따.
import { http, HttpResponse } from 'mse'
export const handlers = [
http.post('/auth', () => {
return new HttpResponse(null, {
headers: {
'Set-Cookie': '~~~',
'X-Custom-Header': 'yes',
},
})
}),
]
Body Mocking
다양한 응답 바디 유형으로 요청에 응답할수 있따
- String
- Blob
- FormData
- ReadableStream
- others..
가장 일반적인 HTTP 응답 바디들
Text responses
HTTP에서 가장 기본적인 응답
HttpResponse 생성자의 인자로 원하는 문자열을 넣어서 mocked text response를 만들어라
import { http, HttpResponse } from 'msw'
export const handler = [
http.get('/name', () => {
return new HttpResponse('John')
}),
]
- HttpResponse.text() 메서드를 사용할수도 있따.
JSON responses
import { http, HttpResponse } from 'msw'
export const handlers = [
http.post('/auth', () => {
return HttpResponse.json({
user: {
id: 'abc-123',
name: 'John Maverick',
},
})
}),
]
Stream responses
https://mswjs.io/docs/recipes/streaming
Other responses
XML, Blob, ArrayBuffer, FormData 같은 타입도 있다
링크 : https://mswjs.io/docs/api/http-response
Mocking error response
에러 응답을 구축하고 반환함
http.get('/user', () => {
// Respond with "401 Unauthorized" to "GET /user" requests.
return HttpResponse(null, {status:401})
})
Mocking network errors
Response.error() 나 HttpResponse.error() 같은 메서드는 네트워크 에러를 발생시키는데 사용한다
에러 응답과 다르게, 네트워크 에러는 요청 실행을 중지시키고 해당 요청을 실패로 표시한다.
실제로는 유효하지 않은 요청을 만들거나 해결할 수 없는 호스트 이름을 요청할 때와 같이 네트워크 에러가 발생함
'front-end > msw' 카테고리의 다른 글
[MSW] 브라우저 환경에서 사용하기 (0) | 2024.01.19 |
---|---|
[MSW] Describing REST API (0) | 2024.01.19 |