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

[Feat] 테스트 코드 초기 세팅 #439

Merged
merged 20 commits into from
Sep 3, 2024
Merged

Conversation

eonseok-jeon
Copy link
Member

@eonseok-jeon eonseok-jeon commented Aug 28, 2024

Related Issue : Closes #433


🧑‍🎤 Summary

  • setupTests.ts 추가
  • custom render 에러 해결
  • 실제 코드로 test 완료

🧑‍🎤 Comment

24.09.02 pr 재생성

오래 걸렸네요 죄송합니두 😓
확실하게 실제 코드를 이용해서 테스트 해봤습니다

custom render 관련 추가된 코드

🫠 fillStyle에 null 값 들어갈 수 없음

lottie 관련해서 fillStyle이 null로 설정되어 테스트를 진행할 수 없다는 에러가 떴어요
스크린샷 2024-09-02 오후 11 12 17
jest-canvas-mock을 설치하라는 답변이 많았지만 분명 라이브러리 설치 하지 않고 다른 방법으로 해결할 수 있을 거 같았어요
물론 저희는 vitest를 사용하니 vitest-canvas-mock을 설치하면 됐습니다! (실제로 해당 라이브러리 설치하면 에러가 사라졌었어요)
어쨌든 다른 방법을 찾아보니 fillStyle에 null이 아닌 '' 빈 문자열을 설정하면 되더라고요
참고자료
추후에 로딩 스피너 관련 테스트 진행할 때 이로 인한 문제가 발생한다면 그때 vitest-canvas-mock을 설치해봐도 좋을 거 같아요 :)

🫠 Router의 부재

Router로 감싸져 있지 않아 useNavigate 등의 hook을 찾을 수 없다는 에러가 떴어요
test를 할 때는 MemoryRouter를 사용해준다고 하는데 (참고자료1, 참고자료2)
저희는 custom render에 전역적으로 적용한 거라
단순 MemoryRouter로 감싸는 걸로 끝나는 것이 아닌
해당 MemoryRouter에 memory router props도 넘겨줄 수 있어야 했어요
따라서 이와 같이 수정해줬어요

test('test', () => {
  render(<ApplyPage />, {}, { initialEntries: ['/test'] });
});

사용은 위와 같은 방법으로 하면 됩니다
기존 render 방식은 그대로 유지한 채 세 번째 인자로 받도록 구현했어요
물론 initialEntries의 default 값은 '/' 라 필요 없다면 추가 안해도 돼요
물론 다른 props 들도 추가할 수 있답니다

그 외는 Provider 추가한 거라 특별한 건 없어요
더 자세한 내용은 makers 노션 - 언석 공부방에 정리해 놨습니다 :)

결과

custom render를 이용한 테스트를 통과하는 걸 확인할 수 있었습니다

import { render, screen } from 'tests/test-utils';
import BottomSection from '../components/BottomSection';
import { userEvent } from '@testing-library/user-event';
import SignInForm from 'views/SignInPage/components/SignInForm';

test('test', () => {
  render(<SignInForm />, {}, { initialEntries: ['/'] });

  const button = screen.getByRole('button', { name: /로그인/i });

  expect(button).toBeEnabled();
});

test('test2', async () => {
  const user = userEvent.setup();
  render(<BottomSection isReview={false} />, {}, { initialEntries: ['/'] });

  const checkbox = screen.getByRole('checkbox', { name: /개인정보/i });
  expect(checkbox).not.toBeChecked();

  await user.click(checkbox);
  expect(checkbox).toBeChecked();

  await user.click(checkbox);
  expect(checkbox).not.toBeChecked();
});
스크린샷 2024-09-02 오후 11 31 28
24.08.28 이전 PR comment

🧑‍🎤 Summary

  • lint, config 설정
  • custom render 생성

🧑‍🎤 Comment

😎 renderWithContext의 목적

test할 때 component를 render 해주는데 context를 적용시켜주기 위해선 wrapper 옵션을 주어 이를 감싸줘야 해요
하지만 매번 그렇게 하긴 귀찮으니 global 하게 설정을 해줄 수가 있어요
context가 필요한 경우 해당 render를 import 하면 되고
필요 없다면 기존 @testing-library/react 에서 제공하는 render를 import 하면 됩니다 :)
참고자료

@auto-assign auto-assign bot requested a review from lydiacho August 28, 2024 08:48
Copy link

height bot commented Aug 28, 2024

Link Height tasks by mentioning a task ID in the pull request title or commit messages, or description and comments with the keyword link (e.g. "Link T-123").

💡Tip: You can also use "Close T-X" to automatically close a task when the pull request is merged.

@eonseok-jeon eonseok-jeon changed the title [Feat] 테스트 코드 추가 [Feat] 테스트 코드 초기 세팅 Aug 28, 2024
Copy link
Member

@lydiacho lydiacho left a comment

Choose a reason for hiding this comment

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

세팅하시느라 고생 많으셨습니다 👍
custom renderer 만든 것도 너무너무 좋아여 !!


혹시 테스트 코드 시험 삼아 실행시켜보셨을까요??
제 환경에서는 현재 세팅으로는 테스트 코드 실행에 실패했는데요ㅠㅠ!

만약 언석님도 동일하게 문제가 발생한다면, 아래의 원인과 해결책을 참고해주시면 좋을 것 같아용

제가 테스트 코드 실행해봤을 때 마주친 트러블의 플로우 순으로 말씀드릴게요!

  1. Cannot find module @testing-library/dom

현재 추가해주신 의존성에 dom 모듈은 없는데요! 아마 이런 내용들을 보시고, react 모듈에 dom 모듈이 포함되어있으니 별도로 설치할 필요 없다고 생각하셨을 것 같아요
하지만 다른 프레임워크 wrapper들과 달리 react 전용 래퍼는 @testing-library/dompeerDependency로 명시해주고 있어요. 즉 개발자가 별도로 설치를 해줘야 한다는 뜻이죠. 공식문서에서도 그렇게 안내하고 있고요!

image

따라서 yarn add -D로 의존성을 추가로 설치해줘야 합니다

  1. Invalid Chai property : ~메소드

의존성 추가 설치 했지만 여전히 테스트는 실패했어요 😢
저는 브라우저 테스트를 해보고 싶어서 toBeDisabled를 사용하는 예제 코드를 작성해서 시험을 돌려봤는데요!
toBeDiabled를 얘가 알아먹지 못해서 실패가 나더라고요.

그래서 다시 해당 API를 제공하는 jest-dom공식문서를 참고한 결과

image

이렇게 vitest와 함께 사용할 경우, setupFile에 별도로 import를 해주는 작업이 필요하다고 해요.

이 문제를 해결하기 위해 공식문서에 나와있는대로
➡️ 언석님이 msw 도입을 위해 주석처리 해두신 setupFiles 부분의 주석을 풀고,
➡️ test > setupTests.ts 파일을 생성한 후,

import '@testing-library/jest-dom/vitest';

이렇게 명시해주고,
➡️ 마지막으로 tsconfig.json의 compilerOptions > include 에도 "./src/tests/setupTests.ts" 를 추가해주면

테스트 코드가 아주 잘 작동하더라구요!


이랬는데 언석님은 문제없이 테스트가 돌아간다면 민망하지만,,
안해보셨다면 한번 확인해보시고 요거 해결 잡고 머지하면 좋을 것 같아여 !!

vite.config.ts Outdated Show resolved Hide resolved
@eonseok-jeon eonseok-jeon marked this pull request as draft August 30, 2024 01:07
@eonseok-jeon eonseok-jeon marked this pull request as ready for review September 2, 2024 14:35
@auto-assign auto-assign bot requested a review from lydiacho September 2, 2024 14:35
Copy link
Member

@lydiacho lydiacho left a comment

Choose a reason for hiding this comment

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

모두 확인했습니다 !!
완전 수고 많으셨습니다 👨‍🎤 👨‍🎤 👨‍🎤 👨‍🎤 👨‍🎤
해당 PR 머지하면 곧 MSW 세팅 작업 할게요 !!

@eonseok-jeon eonseok-jeon merged commit 83f9bf2 into develop Sep 3, 2024
@eonseok-jeon eonseok-jeon deleted the feat/#433_vitest-setting branch September 3, 2024 05:55
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.

[Feat] 테스트 코드 초기 세팅
2 participants