Skip to content

[BUG] Server component에서 msw mocking이 되지 않는 문제 #59

@e-sum-e

Description

@e-sum-e

🌱 버그 설명

상황

Server component에서 msw mocking 시도 시 아래와 같이 에러 발생

  • TypeError: fetch failed
Image Image

현재 mocking하는 코드

export async function initMocks() {
  console.log('initMocks');
  if (process.env.NODE_ENV !== 'development') return;
  **if (typeof window === 'undefined') {
    // 서버 사이드
    const { server } = await import('./server');
    server.listen();
  }** else {
    // 클라이언트 사이드
    const { worker } = await import('./browser');
    await worker.start();
  }
}

원인

실행 환경이 Broswer(Client side)에서만 실행하고 있기 때문에 감지해낼 server side가 없음.

/MSWComponent.tsx
'use client';

import { initMocks } from '@/mocks';
import { useEffect, useState } from 'react';

export const MSWComponent = ({ children }: { children: React.ReactNode }) => {
  const [mswReady, setMswReady] = useState(false);
  useEffect(() => {
    const init = async () => {
      await initMocks(); // 클라이언트에서만 실행되기때문에 해당 파일안에 설정된 서버 분기가 실행되지않음
      setMswReady(true);
    };

    if (!mswReady) {
      init();
    }
  }, [mswReady]);

  if (!mswReady) {
    return null;
  }
  return <>{children}</>;
};

해결 방안

임시로 root layout에서 server.listen() 실행

🔗 참고 링크

mswjs/examples#101


기타

  • MSWComponent가 필요한가? page.tsx에서 바로 init을 해도 될거 같다는 생각입니다.
    -> 추후 리팩토링 고려

Sub-issues

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions