SNS 프로젝트를 진행하면서 아직 백엔드 api 개발이 다 되지않아서 모의 데이터를 만들어야해서 찾아보다가 MSW(Mock Service Worker)를 알게 되어서 프로젝트에 MSW를 적용시켜보았다.
MSW(Mock Service Worker)란?
MSW(Mock Service Worker)는 서비스 워커(Service Worker)를 사용하여 네트워크 호출을 가로채는 API 모킹(mocking) 라이브러리
yarn add -D msw
import { setupWorker } from 'msw';
import { handlers } from './handlers';
export const worker = setupWorker(...handlers);
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,
},
}),
);
}),
];
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 {};
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
// 추가
if (process.env.NEXT_PUBLIC_API_MOCKING === 'enabled') {
import('../mocks');
}
function App({component}) {}
NEXT_PUBLIC_API_MOCKING=enabled
💡 mockServiceWorker파일이 서비스 워커에 mock 서버 등록
npx msw init public/ --save
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/