Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore : axios 세팅 msw 연동 및 테스트 #17

Merged
merged 4 commits into from
Jul 30, 2024
Merged

Conversation

aquaman122
Copy link
Contributor

💡 작업 내용

  • axios 세팅
  • msw 연동 및 테스트

💡 자세한 설명

🛠️ MSW 사용법

mocks/handlers 폴더에 파일 추가 하신 후 browser.ts 파일에 함수? 추가만 해주시면 됩니다.

// test.ts
import { http, HttpHandler, HttpResponse } from 'msw';
import { API_END_POINT } from '@/constants/api';
import ongoingProducts from '../data/ongoingData';

export const getTest: HttpHandler = http.get(
  `${API_END_POINT.TEST}`,
  async () => {
    return new HttpResponse(
      JSON.stringify({
        test: [...ongoingProducts],
      }),
      {
        status: 200,
        statusText: 'OK',
      },
    );
  },
);

export default getTest;
// handler.ts
import { setupWorker } from 'msw/browser';
import { HttpHandler } from 'msw';
import getTest from './handlers/test';

export const handlers: HttpHandler[] = [
  getTest,
];

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

🛠️ axios 연결

utils 폴더 생성 후 axios.ts 파일 생성

// utils/axios.ts

import axios, { AxiosRequestConfig } from 'axios';

export const createClient = (config?: AxiosRequestConfig) => {
  const axiosInstance = axios.create({
    baseURL: import.meta.env.VITE_MOCK_API_URL,
    headers: {
      'Content-Type': 'application/json',
    },
    withCredentials: true,
    timeout: 5000,
    ...config,
  });
  axiosInstance.interceptors.request.use((request) => {
    return request;
  });

  axiosInstance.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      return Promise.reject(error);
    },
  );

  return axiosInstance;
};

export const httpClient = createClient();

🛠️ axios 사용방법

api 폴더에 파일 생성 후 사용 파일 이름은 *.api.ts로 생성

// api/test.api.ts

import { API_END_POINT } from '@/constants/api';
import { TestItems } from '@/pages/Test';
import { httpClient } from '@/utils/axios';

interface TestData {
  test: TestItems[];
}

export const getTest = async (): Promise<TestData> => {
  const response = await httpClient.get(API_END_POINT.TEST);
  return response.data;
};

🛠️ Tanstack-query 사용해서 Test

// Test.tsx

/* eslint-disable import/no-cycle */
import { useQuery } from '@tanstack/react-query';
import { getTest } from '@/api/test.api';
/* eslint-disable import/no-cycle */

export interface TestItems {
  id: number;
  name: string;
  startPrice: string;
  timeLeft: string;
  activeUserCount: string;
  isBidding: boolean;
}

const Test = () => {
  const { data, isLoading, error } = useQuery({
    queryKey: ['TEST'],
    queryFn: () => getTest(),
  });

  if (isLoading) return <div>Loading</div>;
  if (error) return <div>Error</div>;

  return (
    <div>
      {data?.test?.map(
        (
          item: any /* eslint-disable-line @typescript-eslint/no-explicit-any */,
          index: number /* eslint-disable-line @typescript-eslint/no-unused-vars */,
        ) => <div key={item.id}>{item.name}</div>,
      )}
    </div>
  );
};

export default Test;
스크린샷 2024-07-30 오전 12 05 22 스크린샷 2024-07-30 오전 12 06 15 스크린샷 2024-07-30 오전 12 06 24

📗 참고 자료 (선택)

📢 리뷰 요구 사항 (선택)

🚩 후속 작업 (선택)

✅ 셀프 체크리스트

  • PR 제목을 형식에 맞게 작성했나요?
  • 브랜치 전략에 맞는 브랜치에 PR을 올리고 있나요? (master/main이 아닙니다.)
  • 이슈는 close 했나요?
  • Reviewers, Labels, Projects를 등록했나요?
  • 작업 도중 문서 수정이 필요한 경우 잘 수정했나요?
  • 테스트는 잘 통과했나요?
  • 불필요한 코드는 제거했나요?

closes #이슈번호

@aquaman122 aquaman122 added the ⚙️chore 세팅 관련 label Jul 29, 2024
@aquaman122 aquaman122 self-assigned this Jul 29, 2024
@aquaman122 aquaman122 merged commit 704e006 into dev Jul 30, 2024
@aquaman122 aquaman122 deleted the chore/axios-setting branch July 30, 2024 05:58
@aquaman122 aquaman122 changed the title chore : axios 세팅 msw 연동 및 테스트 Chore : axios 세팅 msw 연동 및 테스트 Aug 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⚙️chore 세팅 관련
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant