Skip to content

Comments

[test] LazyImage 컴포넌트 테스트 추가#333

Merged
seongwon030 merged 8 commits intodevelop-fefrom
feature/#332-improve-lazy-image-component-FE-88
Apr 28, 2025
Merged

[test] LazyImage 컴포넌트 테스트 추가#333
seongwon030 merged 8 commits intodevelop-fefrom
feature/#332-improve-lazy-image-component-FE-88

Conversation

@seongwon030
Copy link
Member

@seongwon030 seongwon030 commented Apr 26, 2025

#️⃣연관된 이슈

ex) #332

📝작업 내용

  • 이미지 렌더링 테스트를 위한 react-testing-libray 설치
  • 렌더링하고, 클릭하고, 입력하는 식의 행동(Behavior) 을 테스트를 위해 @testing-library/jest-dom설치
  • 테스트 커버리지 보여주는 jest --coverage scripts에 추가

jest 사용했을 때

expect(button).not.toBeNull(); // 버튼이 존재하는지만 확인
expect(button.disabled).toBe(true); // 버튼이 비활성화됐는지 검사

jestdom 사용했을 때

expect(button).toBeInTheDocument();  // 문서에 존재하는지
expect(button).toBeDisabled();       // 비활성화됐는지

적용 이유

  • jest의 메서드로는 원시값 비교밖에 못하기 때문에 ui 테스트하기 불편함
  • 보다 선언적인 테스트를 할 수 있음

LazyImage 테스트

IntersectionObserver에 대하여

가짜 함수

const mockIntersectionObserver = jest.fn();
const mockDisconnect = jest.fn();
const mockObserve = jest.fn();

jest.fn()은 가짜함수를 만들어줍니다.
만드는 이유는 테스트파일이 의존성을 줄이기 위해서입니다. 만약 테스트할 함수가 api 요청을 하는 함수라면
오로지 테스트를 위한 요청이 만들어집니다. 이는 불필요하기 때문에 가짜함수를 만들었습니다.

가짜 IntersectionObserver

Object.defineProperty(window, 'IntersectionObserver', {
  writable: true,
  configurable: true,
  value: MockIntersectionObserver,
});
  • jest환경에서는 IntersectionObserver가 없습니다.
  • 진짜 브라우저를 대체할 가짜 IntersectionObserver로 대체하여 프로젝트에서 컴포넌트가 정상적으로 동작하는지를 확인합니다.

테스트

  it('초기에는 이미지가 로드되지 않고 플레이스홀더가 표시되어야 함', () => {
    render(<LazyImage {...defaultProps} />);

    const placeholder = screen.getByTestId('lazy-image-placeholder');
    expect(placeholder).toBeInTheDocument();
    expect(placeholder).toHaveStyle({ backgroundColor: '#f0f0f0' });

    const img = screen.queryByRole('img');
    expect(img).not.toBeInTheDocument();
  });
  • render: 말그대로 컴포넌트가 렌더링 되는지 확인합니다.
  • 렌더링 직후, 이미지 대신 placeholder가 표시되는지 테스트 추가
  • placeholder 배경색(background-color: #f0f0f0) 확인
  • 이미지(img) 요소는 존재하지 않아야 함

참고자료

before/after
프론트엔드 테스트 | jest 기본 정리
waitFor을 통한 비동기 함수 테스트
jest 테스트 커버리지

중점적으로 리뷰받고 싶은 부분(선택)

리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요

ex) 메서드 XXX의 이름을 더 잘 짓고 싶은데 혹시 좋은 명칭이 있을까요?

논의하고 싶은 부분(선택)

논의하고 싶은 부분이 있다면 작성해주세요.

🫡 참고사항

Summary by CodeRabbit

Summary by CodeRabbit

  • Tests
    • LazyImage 컴포넌트에 대한 새로운 테스트가 추가되어 다양한 동작을 검증합니다.
  • Chores
    • 테스트 도구 관련 개발 의존성이 추가되고, 커버리지 측정용 npm 스크립트가 추가되었습니다.
    • 커버리지 리포트 디렉토리가 Git 추적에서 제외되었습니다.
  • Style
    • LazyImage 컴포넌트의 플레이스홀더에 테스트 식별자 속성이 추가되었습니다.
  • Refactor
    • Jest 설정이 개선되어 코드 커버리지 수집 및 보고가 활성화되었습니다.

- IntersectionObserver 모킹하여 LazyImage 렌더링 상황 제어
- 초기 렌더링, 지연 로딩, 에러 핸들링, unmount 시 처리 테스트
- index, delayMs props에 따른 지연 로딩 테스트
@seongwon030 seongwon030 added ✅ Test test 관련(storybook, jest...) 💻 FE Frontend labels Apr 26, 2025
@seongwon030 seongwon030 requested review from Copilot and oesnuj April 26, 2025 10:59
@seongwon030 seongwon030 self-assigned this Apr 26, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 26, 2025

"""

Walkthrough

이번 변경에서는 LazyImage 컴포넌트의 테스트 파일이 새롭게 추가되고, 테스트 편의를 위해 컴포넌트의 placeholder에 data-testid 속성이 부여되었습니다. 또한, 테스트 환경 구축을 위해 @testing-library/jest-dom@testing-library/react 패키지가 프론트엔드 개발 의존성에 추가되었고, Jest 커버리지 실행을 위한 npm 스크립트가 추가되었습니다. 커버리지 결과물이 저장되는 coverage/ 디렉터리는 .gitignore에 등록되어 버전 관리에서 제외됩니다. 기존 컴포넌트의 로직에는 영향이 없으며, 테스트 신뢰성과 유지보수성을 높이기 위한 변경이 이루어졌습니다.

Changes

파일/경로 변경 요약
frontend/package.json @testing-library/jest-dom, @testing-library/react devDependencies 추가 및 coverage npm 스크립트 추가
frontend/.gitignore coverage/ 디렉터리 git 무시 설정 추가
frontend/jest.config.js Jest 설정 수정: TypeScript 변환 regex 수정, 커버리지 수집 활성화 및 출력 경로/포맷 지정
frontend/src/components/common/LazyImage/LazyImage.test.tsx LazyImage 컴포넌트 테스트 신규 작성, IntersectionObserver 모킹 구현 및 다양한 동작 검증
frontend/src/components/common/LazyImage/LazyImage.tsx placeholder <div>data-testid='lazy-image-placeholder' 속성 추가

Sequence Diagram(s)

sequenceDiagram
    participant Test as LazyImage.test.tsx
    participant LazyImage as LazyImage Component
    participant MockIO as MockIntersectionObserver
    participant DOM as DOM

    Test->>LazyImage: 렌더링 요청 (props 전달)
    LazyImage->>MockIO: IntersectionObserver 등록
    MockIO-->>LazyImage: observe 콜백 호출 (intersecting 여부)
    LazyImage->>DOM: placeholder 또는 이미지 렌더링
    Test->>DOM: placeholder, 이미지, alt 속성 등 검증
    Test->>LazyImage: unmount (컴포넌트 해제)
    LazyImage->>MockIO: disconnect 호출
Loading

Assessment against linked issues

Objective Addressed Explanation
LazyImage 컴포넌트 개선 및 테스트 추가 (FE-88)
"""

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73d0417 and de0a4b4.

📒 Files selected for processing (1)
  • frontend/jest.config.js (1 hunks)
🔇 Additional comments (2)
frontend/jest.config.js (2)

6-6: TypeScript 파일의 정규식 패턴이 올바르게 수정되었습니다.

\\.tsx?$ 패턴에서 백슬래시가 올바르게 이스케이프되어 있어 .ts.tsx 파일을 정확히 찾을 수 있습니다. 이전에는 이 부분에 문제가 있었을 수 있습니다.


11-18: 테스트 커버리지 설정이 적절하게 구성되었습니다.

코드 커버리지 수집을 위한 설정이 잘 추가되었습니다:

  • collectCoverage: true로 설정하여 테스트 실행 시 자동으로 커버리지 정보를 수집합니다.
  • 커버리지 결과물은 'coverage' 디렉토리에 저장됩니다.
  • 콘솔 출력용 'text'와 Codecov 통합용 'lcov' 리포터가 적절히 설정되었습니다.
  • 커버리지 수집 대상도 적절하게 설정되어 있으며, 타입 선언 파일과 인덱스 파일을 제외한 것은 좋은 접근입니다.

이 설정은 PR 목적에 맞게 LazyImage 컴포넌트 테스트의 커버리지를 효과적으로 측정할 수 있게 해줍니다.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds tests for the LazyImage component to verify its lazy loading behavior, IntersectionObserver integration, error handling, and proper unmounting.

  • Added a data-testid attribute to the placeholder in LazyImage.tsx.
  • Introduced comprehensive tests in LazyImage.test.tsx covering image loading, delay handling, IntersectionObserver callbacks, error propagation, and observer cleanup.

Reviewed Changes

Copilot reviewed 2 out of 4 changed files in this pull request and generated no comments.

File Description
frontend/src/components/common/LazyImage/LazyImage.tsx Added data-testid for testing the placeholder element.
frontend/src/components/common/LazyImage/LazyImage.test.tsx Added tests for lazy loading, delay behavior, IntersectionObserver integration, and onError behavior.
Files not reviewed (2)
  • frontend/package-lock.json: Language not supported
  • frontend/package.json: Language not supported

@netlify
Copy link

netlify bot commented Apr 26, 2025

Deploy Preview for moadong ready!

Name Link
🔨 Latest commit de0a4b4
🔍 Latest deploy log https://app.netlify.com/sites/moadong/deploys/680e637cc0ac1d000853136f
😎 Deploy Preview https://deploy-preview-333--moadong.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 31
Accessibility: 87
Best Practices: 92
SEO: 85
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Member

@oesnuj oesnuj left a comment

Choose a reason for hiding this comment

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

UI 테스트도 적용해봅시다
좋아요~~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

💻 FE Frontend ✅ Test test 관련(storybook, jest...)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[feature] FE-88 LazyImage 컴포넌트 테스트 추가

2 participants