Skip to content

Commit

Permalink
[FE] [email protected][email protected] 으로 마이그레이션 (#979)
Browse files Browse the repository at this point in the history
* chore: msw, msw-storybook-addon의 버전을 최신 버전으로 업데이트

- msw의 최신 버전과 msw-storybook-addon의 구버전의 peer dependencies가 일치하지 않아 msw-storybook-addon도 업데이트를 진행

* chore: msw를 `2.1.7`로, msw-storybook-addon의 버전을 최신 버전으로 업데이트

- msw의 `2`버전과 msw-storybook-addon의 구버전의 peer dependencies가 일치하지 않아 msw-storybook-addon도 업데이트를 진행
- msw를 최신 버전으로 업데이트 하지 않는 이유는 `2.1.7` 보다 높은 버전에서 "Cannot read properties of undefined (reading 'url')" 가 발생하기 때문

* chore: mockServiceWorker.js를 생성

* chore: 지금까지의 핸들러 모킹 코드들을 `v2`로 마이그레이션

* chore: msw가 실행되는 시점을 렌더링 이전 시점으로 두도록 변경

- 간헐적인 에러가 발생하는 것을 방지

* chore: http 모듈에 요청 시의 body 타입을 추가

- `v1`과 달리 `v2`는 `response.json()`이 `any`로 추론되지 않으며, 이로 인해 타입 에러가 발생함
- 따라서 제네릭을 이용해 body의 타입을 지정

* chore: msw를 최신 버전으로 업데이트

- 제시되었던 오류가 해결된 것으로 확인
  • Loading branch information
wzrabbit authored Dec 31, 2024
1 parent d482d45 commit 0d72df5
Show file tree
Hide file tree
Showing 10 changed files with 9,416 additions and 3,839 deletions.
12,565 changes: 9,065 additions & 3,500 deletions frontend/package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@
"jest": "^29.6.0",
"lint-staged": "^13.2.3",
"mini-css-extract-plugin": "^2.7.6",
"msw": "^1.2.3",
"msw-storybook-addon": "^1.8.0",
"msw": "^2.7.0",
"msw-storybook-addon": "^2.0.4",
"prettier": "3.0.0",
"storybook": "^7.0.26",
"tsconfig-paths-webpack-plugin": "^4.0.1",
Expand Down
206 changes: 105 additions & 101 deletions frontend/public/mockServiceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
/* tslint:disable */

/**
* Mock Service Worker (1.2.3).
* Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
*/

const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'
const PACKAGE_VERSION = '2.7.0'
const INTEGRITY_CHECKSUM = '00729d72e3b82faf54ca8b9621dbb96f'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()

self.addEventListener('install', function () {
Expand Down Expand Up @@ -47,7 +49,10 @@ self.addEventListener('message', async function (event) {
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: INTEGRITY_CHECKSUM,
payload: {
packageVersion: PACKAGE_VERSION,
checksum: INTEGRITY_CHECKSUM,
},
})
break
}
Expand All @@ -57,7 +62,12 @@ self.addEventListener('message', async function (event) {

sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: true,
payload: {
client: {
id: client.id,
frameType: client.frameType,
},
},
})
break
}
Expand Down Expand Up @@ -86,12 +96,6 @@ self.addEventListener('message', async function (event) {

self.addEventListener('fetch', function (event) {
const { request } = event
const accept = request.headers.get('accept') || ''

// Bypass server-sent events.
if (accept.includes('text/event-stream')) {
return
}

// Bypass navigation requests.
if (request.mode === 'navigate') {
Expand All @@ -112,29 +116,8 @@ self.addEventListener('fetch', function (event) {
}

// Generate unique request ID.
const requestId = Math.random().toString(16).slice(2)

event.respondWith(
handleRequest(event, requestId).catch((error) => {
if (error.name === 'NetworkError') {
console.warn(
'[MSW] Successfully emulated a network error for the "%s %s" request.',
request.method,
request.url,
)
return
}

// At this point, any exception indicates an issue with the original request/response.
console.error(
`\
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
request.method,
request.url,
`${error.name}: ${error.message}`,
)
}),
)
const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId))
})

async function handleRequest(event, requestId) {
Expand All @@ -146,21 +129,24 @@ async function handleRequest(event, requestId) {
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
;(async function () {
const clonedResponse = response.clone()
sendToClient(client, {
type: 'RESPONSE',
payload: {
requestId,
type: clonedResponse.type,
ok: clonedResponse.ok,
status: clonedResponse.status,
statusText: clonedResponse.statusText,
body:
clonedResponse.body === null ? null : await clonedResponse.text(),
headers: Object.fromEntries(clonedResponse.headers.entries()),
redirected: clonedResponse.redirected,
const responseClone = response.clone()

sendToClient(
client,
{
type: 'RESPONSE',
payload: {
requestId,
isMockedResponse: IS_MOCKED_RESPONSE in response,
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
body: responseClone.body,
headers: Object.fromEntries(responseClone.headers.entries()),
},
},
})
[responseClone.body],
)
})()
}

Expand All @@ -174,6 +160,10 @@ async function handleRequest(event, requestId) {
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)

if (activeClientIds.has(event.clientId)) {
return client
}

if (client?.frameType === 'top-level') {
return client
}
Expand All @@ -196,20 +186,34 @@ async function resolveMainClient(event) {

async function getResponse(event, client, requestId) {
const { request } = event
const clonedRequest = request.clone()

// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const requestClone = request.clone()

function passthrough() {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const headers = Object.fromEntries(clonedRequest.headers.entries())
// Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
const headers = new Headers(requestClone.headers)

// Remove the "accept" header value that marked this request as passthrough.
// This prevents request alteration and also keeps it compliant with the
// user-defined CORS policies.
const acceptHeader = headers.get('accept')
if (acceptHeader) {
const values = acceptHeader.split(',').map((value) => value.trim())
const filteredValues = values.filter(
(value) => value !== 'msw/passthrough',
)

// Remove MSW-specific request headers so the bypassed requests
// comply with the server's CORS preflight check.
// Operate with the headers as an object because request "Headers"
// are immutable.
delete headers['x-msw-bypass']
if (filteredValues.length > 0) {
headers.set('accept', filteredValues.join(', '))
} else {
headers.delete('accept')
}
}

return fetch(clonedRequest, { headers })
return fetch(requestClone, { headers })
}

// Bypass mocking when the client is not active.
Expand All @@ -225,57 +229,46 @@ async function getResponse(event, client, requestId) {
return passthrough()
}

// Bypass requests with the explicit bypass header.
// Such requests can be issued by "ctx.fetch()".
if (request.headers.get('x-msw-bypass') === 'true') {
return passthrough()
}

// Notify the client that a request has been intercepted.
const clientMessage = await sendToClient(client, {
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
mode: request.mode,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: await request.text(),
bodyUsed: request.bodyUsed,
keepalive: request.keepalive,
const requestBuffer = await request.arrayBuffer()
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: requestBuffer,
keepalive: request.keepalive,
},
},
})
[requestBuffer],
)

switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
return respondWithMock(clientMessage.data)
}

case 'MOCK_NOT_FOUND': {
case 'PASSTHROUGH': {
return passthrough()
}

case 'NETWORK_ERROR': {
const { name, message } = clientMessage.data
const networkError = new Error(message)
networkError.name = name

// Rejecting a "respondWith" promise emulates a network error.
throw networkError
}
}

return passthrough()
}

function sendToClient(client, message) {
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()

Expand All @@ -287,17 +280,28 @@ function sendToClient(client, message) {
resolve(event.data)
}

client.postMessage(message, [channel.port2])
client.postMessage(
message,
[channel.port2].concat(transferrables.filter(Boolean)),
)
})
}

function sleep(timeMs) {
return new Promise((resolve) => {
setTimeout(resolve, timeMs)
async function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
return Response.error()
}

const mockedResponse = new Response(response.body, response)

Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})
}

async function respondWithMock(response) {
await sleep(response.delay)
return new Response(response.body, response)
return mockedResponse
}
50 changes: 28 additions & 22 deletions frontend/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@ import { TokenProvider } from '~/contexts/TokenContext';
import { useToast } from '~/hooks/useToast';
import GlobalStyle from '~/styles/GlobalStyle';
import { theme } from './styles/theme';
import { worker } from '~/mocks/browser';

if (process.env.WORKER === 'on') {
worker.start();
}
const enableMocking = async () => {
if (process.env.NODE_ENV === 'production') {
return;
}

const { worker } = await import('./mocks/browser');
await worker.start();
};

const _QueryClientProvider = ({ children }: { children: ReactNode }) => {
const { showToast } = useToast();
Expand Down Expand Up @@ -61,21 +65,23 @@ const _QueryClientProvider = ({ children }: { children: ReactNode }) => {

const root = createRoot(document.getElementById('root') as HTMLElement);

root.render(
<StrictMode>
<ThemeProvider theme={theme}>
<ToastProvider>
<TokenProvider>
<_QueryClientProvider>
<GlobalStyle />
<BrowserRouter>
<App />
</BrowserRouter>
<ToastList />
<ReactQueryDevtools initialIsOpen={false} />
</_QueryClientProvider>
</TokenProvider>
</ToastProvider>
</ThemeProvider>
</StrictMode>,
);
enableMocking().then(() => {
root.render(
<StrictMode>
<ThemeProvider theme={theme}>
<ToastProvider>
<TokenProvider>
<_QueryClientProvider>
<GlobalStyle />
<BrowserRouter>
<App />
</BrowserRouter>
<ToastList />
<ReactQueryDevtools initialIsOpen={false} />
</_QueryClientProvider>
</TokenProvider>
</ToastProvider>
</ThemeProvider>
</StrictMode>,
);
});
2 changes: 1 addition & 1 deletion frontend/src/mocks/browser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { setupWorker } from 'msw';
import { setupWorker } from 'msw/browser';
import { handlers } from '~/mocks/handlers';

export const worker = setupWorker(...handlers);
Loading

0 comments on commit 0d72df5

Please sign in to comment.