MSW 적용 (next.js, typescript)

MyungjuKang (강명주)·2023년 5월 22일
1

SNS 프로젝트를 진행하면서 아직 백엔드 api 개발이 다 되지않아서 모의 데이터를 만들어야해서 찾아보다가 MSW(Mock Service Worker)를 알게 되어서 프로젝트에 MSW를 적용시켜보았다.

MSW(Mock Service Worker)란?

MSW(Mock Service Worker)는 서비스 워커(Service Worker)를 사용하여 네트워크 호출을 가로채는 API 모킹(mocking) 라이브러리

1. 라이브러리 설치

yarn add -D msw

2. Mocks 디렉터리 생성

3. 파일 생성 및 코드 추가

  • browser.ts 생성
import { setupWorker } from 'msw';
import { handlers } from './handlers';

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

  • handlers.ts 생성
import { rest } from 'msw';

export const handlers = [
  rest.get('https://example.com/feeds', (req, res, ctx) => {
    return res(
      ctx.json({
        status: 'SUCCESS',
        data: {
          items: [
            {
              id: 1,
              description: 'some description #new #newer',
              likeCount: 0,
              commentCount: 0,
              feedImage: [],
              comment: [],
              tag: [
                {
                  tagName: 'new',
                },
                {
                  tagName: 'newer',
                },
              ],
            },
            {
              id: 2,
              description: 'some description #dev #develop',
              likeCount: 12,
              commentCount: 1,
              feedImage: [],
              comment: [
                {
                  userId: 5,
                  feedId: 2,
                  replyCount: 2,
                  comment:
                    '내용',
                },
              ],
              tag: [
                {
                  tagName: 'dev',
                },
                {
                  tagName: 'develop',
                },
              ],
            },
          ],
          totalCount: 2,
        },
      }),
    );
  }),
];
  • index.ts 생성
if (typeof window === 'undefined') {
  const server = import('./server');
  server.then((s) => s.server.listen());
} else {
  const worker = import('./browser');
  worker.then((w) => w.worker.start());
}

export {};
  • server.ts 생성
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);
  • _app.tsx 수정
// 추가
if (process.env.NEXT_PUBLIC_API_MOCKING === 'enabled') {
  import('../mocks');
}

function App({component}) {}
  • .env 파일 생성
NEXT_PUBLIC_API_MOCKING=enabled

4. mockServiceWorker 파일을 생성

💡 mockServiceWorker파일이 서비스 워커에 mock 서버 등록

npx msw init public/ --save

5. API 호출

import axios from 'axios';
import type { InferGetServerSidePropsType } from 'next';

interface Feed {
  id: string;
  description: string;
  likeCount: number;
  commentCount: number;
  feedImage: string[];
  comment: string[];
  tag: string[];
}

const Example = ({
  feeds,
}: InferGetServerSidePropsType<typeof getServerSideProps>) => {
  return (
    <>
      {feeds &&
        feeds.map((feed: Feed) => (
          <div key={feed.id}>
            <p>{'id: ' + feed.id}</p>
            <p>{'description: ' + feed.description}</p>
            <p>{'likeCount: ' + feed.likeCount}</p>
            <p>{'commentCount: ' + feed.commentCount}</p>
            <br />
          </div>
        ))}
    </>
  );
};

export async function getServerSideProps() {
  const res = await axios.get('https://example.com/feeds');
  const feeds: Feed[] = res.data.data.items;

  return {
    props: {
      feeds,
    },
  };
}

export default Example;

🚀 실행 화면


참고
https://somedaycode.tistory.com/27
https://velog.io/@sssssssssy/React-library-MSW
https://dev.classmethod.jp/articles/msw-nextjs-typescript/

profile
생각하는 개발자

0개의 댓글