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

[ Feature/quiz 30 ] 문제풀이 단위 컴포넌트 및 테스트 코드 개발 #45

Merged
merged 54 commits into from
Jun 14, 2024

Conversation

Happhee
Copy link
Collaborator

@Happhee Happhee commented Jun 14, 2024

🔥 Related Issues

resolve #30
close #30

💜 작업 내용

  • problem/[problemId] 구조로 페이지 구현
  • 문제풀이 과정에서 필요한 단위 컴포넌트 개발
  • api mocking하여 test 코드 작성

✅ PR Point

ProblemContextInfo

정답 선택지와 답을 관리하는 context 구현..!

export type ProblemContextInfo = {
  states: {
    choiceAnswer: string | null;
    answer: string | null;
  };
  actions: {
    updateChoiceAnswer: (choiceAnswer: string) => void;
    updateAnswer: (answer: string) => void;
  };
};

params test

아래처럼 모킹을 했습니다..!

vi.mock("next/navigation", () => {
  return {
    __esModule: true,
    useRouter: () => ({
      push: vi.fn(),
      replace: vi.fn(),
      prefetch: vi.fn(),
    }),
    useParams: () => ({
      get: () => {},
      query: {
        problemId: "1",
      },
    }),
  };
});

query 를 불러오고 데이터가 잘 컴포넌트에 렌더링 되는지 테스트

// mutation은 버튼 이벤트를 발생
 const button = screen.getByRole("button");
    await userEvent.click(button);

// get은 renderhook 구현 👉 이부분은 음..query전용 테스트로 분리해도 괜찮을것같기도 합니다..!
 await waitFor(() => renderWithQueryClient());
    const { result } = renderHook(
      () =>
        useQuery({
          ...getProblemQueryOptions({ problemId: 1 }),
        }),
      { wrapper },
    );
    await waitFor(() => result.current.isSuccess);

    expect(screen.getByText("유동성"));
    expect(screen.getByText("분산투자"));
    expect(screen.getByText("높은 운용 비용"));
    expect(screen.getByText("투명성"));

AnswerChoiceButton.tsx + ChoiceFillCircleSvg

  • 버튼 색상 상태는 총 4가지 입니다.
  1. 정답 제출 전 선택 전
  2. 정답 제출 전 선택 후
  3. 정답 제출 후 정답
  4. 정답 제출 후 오답

이에 대한 className이 달라지기에 svg fill 속성을 업데이트 하기 위해 state로 관리했습니다.
test코드는 4가지 경우로 나눠서 작업했습니다.

😡 Trouble Shooting

  • AnswerChoiceButton 스토리 -> msw 입혀서 ui 테스트 진행하는 과정 아직 작업중입니다.
  • msw 활성화되어도 api 요청 한번 실패하는 현상 발생

👀 스크린샷 / GIF / 링크

image
image
image

📚 Reference

Happhee added 30 commits June 9, 2024 12:24
- Q, Quarterly processing of correct and incorrect answers
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 이거 따로 함수로 파서 했었는데 이거 사용하면 될 것 같습니다


const isMockingMode = process.env.NEXT_PUBLIC_API_MOCKING === "enable";

export default function MSWProviders({ children }: PropsWithChildren) {
const [mswReady, setMSWReady] = useState(() => !isMockingMode);
const isMockingModeRef = useRef(!isMockingMode);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 Ref 는 왜 필요한가용??

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

state가 업데이트 되기전에 init이 두번호출되어서 렌더링 업데이트보다 먼저 값을 업데이트 할 수 있는 ref를 만들었습니다.

import { getProblemQueryOptions } from "@problem/remotes/getProblemQueryOptions";
import { render, renderHook, screen, waitFor } from "@testing-library/react";

vi.mock("next/navigation", () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useRouter, useParams 모킹 부분은 setup 쪽으로 빼면 어떨까용?!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

params 인자가 다른데 setup으로 빼도 되는건가요?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 그렇네요..! 인자가 달라서 일단 테스트별로 써야겠네용

...getProblemQueryOptions({ problemId: problemIdNumber }),
});

if (!problemInfo) return <div>error</div>;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 에러뷰.. 저도 아직 처리 안했는데 조만간 컴포넌트로 만들죵!!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

svg 아이콘들을 크기별로 관리하지 말고 그냥 이렇게 컴포넌트로 관리할까용?
크기 조정 + 색 조정 가능하도록...?
https://velog.io/@juno7803/React-React%EC%97%90%EC%84%9C-SVG-%ED%99%9C%EC%9A%A9%ED%95%98%EA%B8%B0#react%EC%97%90%EC%84%9C-%EC%8D%A8%EB%B3%B4%EA%B8%B0

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@soomin9106 지금 이미 저렇게 사용가능하긴한데,.,, 저건 fill 속성이 svg 태그 내부에 들어가야해서 어쩔수없이 만든거야..!
사이즈 조정되니 크기별로 분리안해도 괜찮을것같기두!

@Happhee Happhee merged commit d0efa5a into develop Jun 14, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants