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

[1팀 권준우] [Chapter 2-2] 디자인 패턴과 함수형 프로그래밍 #22

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
b7d8ab2
feat: 구조 설계 md 추가
CreatyJohnKwon Jan 14, 2025
f64cc89
fix: 상품의 엔티티 상태를 관리하는 useProduct.ts 업데이트
CreatyJohnKwon Jan 14, 2025
ad9e0ad
fix: 장바구니 컴포넌트 관심사 분리
CreatyJohnKwon Jan 14, 2025
4ce3b01
fix: 상품 업데이트 로직 개선
CreatyJohnKwon Jan 15, 2025
aeb98c1
fix: 엔티티를 모듈화
CreatyJohnKwon Jan 15, 2025
dd4438c
fix: CartPage 합성 컴포넌트 추가
CreatyJohnKwon Jan 15, 2025
f7a2367
refactor: useCart 구현
CreatyJohnKwon Jan 15, 2025
bc8de7f
refactor: 모듈 구조 수정
CreatyJohnKwon Jan 15, 2025
a9f6c2f
refactor: useCoupon 구현
CreatyJohnKwon Jan 15, 2025
b920169
fix: stock 을 타겟하여 수정되도록 오류 개선
CreatyJohnKwon Jan 15, 2025
fb299e5
refactor: 엔티티 datas 모듈로 분리
CreatyJohnKwon Jan 15, 2025
566b49b
fix: 라이브러리 버전 동기화 오류 개선
CreatyJohnKwon Jan 15, 2025
05f8f5b
refactor: cartUtil 계산함수 구현 완료
CreatyJohnKwon Jan 16, 2025
4cf385f
refactor: 합성 컴포넌트 분리 개선
CreatyJohnKwon Jan 16, 2025
55e269e
refactor: useCart 훅 개선
CreatyJohnKwon Jan 16, 2025
f59861c
refactor: cart 폴더 이전
CreatyJohnKwon Jan 16, 2025
021080e
fix: props 네이밍 오류 수정
CreatyJohnKwon Jan 16, 2025
f53a07a
refactor: discountUtils 분리
CreatyJohnKwon Jan 16, 2025
3da1344
refactor: useAdmin 훅 생성
CreatyJohnKwon Jan 16, 2025
6490ee3
refactor: setCart 에서 cartUtils 로직 반영
CreatyJohnKwon Jan 16, 2025
d19bec6
refactor: 심화과제 테스트 코드 작성
CreatyJohnKwon Jan 16, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
refactor: 심화과제 테스트 코드 작성
  • Loading branch information
CreatyJohnKwon committed Jan 16, 2025
commit d19bec6211ca15c5d52aba61c1b1fa6d24ed1acd
83 changes: 34 additions & 49 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,74 +7,59 @@
- Component에서 비즈니스 로직을 분리하기
- 비즈니스 로직에서 특정 엔티티만 다루는 계산을 분리하기

- [ ] Component에서 사용되는 Data가 아닌 로직들은 hook으로 옮겨졌나요?
- [ ] 주어진 hook의 책임에 맞도록 코드가 분리가 되었나요?
- [ ] 계산함수는 순수함수로 작성이 되었나요?
- [x] Component에서 사용되는 Data가 아닌 로직들은 hook으로 옮겨졌나요?
- [x] 주어진 hook의 책임에 맞도록 코드가 분리가 되었나요?
- [x] 계산함수는 순수함수로 작성이 되었나요?

### 심화과제

- 뷰데이터와 엔티티데이터의 분리에 대한 이해
- 엔티티 -> 리파지토리 -> 유즈케이스 -> UI 계층에 대한 이해

- [ ] Component에서 사용되는 Data가 아닌 로직들은 hook으로 옮겨졌나요?
- [ ] 주어진 hook의 책임에 맞도록 코드가 분리가 되었나요?
- [ ] 계산함수는 순수함수로 작성이 되었나요?
- [ ] 특정 Entitiy만 다루는 함수는 분리되어 있나요?
- [ ] 특정 Entitiy만 다루는 Component와 UI를 다루는 Component는 분리되어 있나요?
- [ ] 데이터 흐름에 맞는 계층구조를 이루고 의존성이 맞게 작성이 되었나요?
- [x] Component에서 사용되는 Data가 아닌 로직들은 hook으로 옮겨졌나요?
- [x] 주어진 hook의 책임에 맞도록 코드가 분리가 되었나요?
- [x] 계산함수는 순수함수로 작성이 되었나요?
- [x] 특정 Entitiy만 다루는 함수는 분리되어 있나요?
- [x] 특정 Entitiy만 다루는 Component와 UI를 다루는 Component는 분리되어 있나요?
- [x] 데이터 흐름에 맞는 계층구조를 이루고 의존성이 맞게 작성이 되었나요?

## 과제를 시작하면서
어떻게 시작해야할까…?

발제로 알 수 있는 이번 과제의 목표는<br/>
모든 소프트웨어에 적절히 존재하는 계층(Component)을 적절히 정리정돈 하는 것
발제로 알 수 있는 이번 과제의 목표<br/>
* 모든 소프트웨어에 적절히 존재하는 주요 계층에 따라 적절히 리팩토링 할 수 있다

여기서 React 의 주요 역할계층은 세 가지가 있다
- Component (컴포넌트)
- Hook (리액트 훅)
- Calc function (계산 함수)
- ….
주요 분류 계층은 엔티티다
* Hook (훅)
* Calc function (계산 함수)
* Component (컴포넌트)

처음으로 해야하는 것은 주어진 발제 자료에 따라 컴포넌트를 분리해보자

합성 컴포넌트 패턴과 자식 Props 패턴

이제 내가 해야하는 것은 두 가지 옵션이다

엔티티 / 계산 함수 / UI
(함수에서는 map, filter, foreach 등으로 조건 반복문을 다룬다)

먼저 커스텀 훅에서는 엔티티와 계산 함수를 다루는데<br/>
UI 를 다루기 보다는 리액트 훅을 적절히 사용 하여 데이터를 컨트롤 하는 목적이 있다

그러므로 UI 는 재사용성과 유연성을 극대화하는 목적으로 합성 컴포넌트 패턴 으로 리팩토링 한다<br/>
또한 자식 Props 패턴으로 부모 컴포넌트에서 커스텀 훅을 호출하고<br/>
반환된 데이터를 자식 컴포넌트에 Props 로 전달하는 최적의 단계를 수행한다

위 고민들을 가지고 리팩토링 과정의 목표를 정해보자면
각각 계층은 무슨 역할을 하는지 자세히 알아보자
1. hooks 에서는 리액트 훅을 사용해서 엔티티를 다룬다<br/>
2. utils 에서는 계산 로직이 포함 된 순수 함수만을 다룬다<br/>
3. components 에서는 hooks 와 utils 에 비지니스 로직을 맡기고<br/>합성 컴포넌트를 적절히 수행해 책임을 나눈다

###### (지피티 첨가 버전)

최종 설계 단계
1. 커스텀 훅에서 데이터와 로직 분리
* 상태 관리와 비즈니스 로직은 커스텀 훅에서 담당합니다.
* map, filter, reduce 등의 메서드를 활용해 데이터를 변환하거나 조건에 따른 동작을 처리합니다.
2. UI 컴포넌트를 합성 컴포넌트 패턴으로 설계
* UI 컴포넌트를 작은 단위로 나누고, Props를 활용해 데이터를 전달받아 렌더링합니다.
* UI와 로직 간의 의존성을 제거합니다.
3. 부모 컴포넌트에서 데이터와 UI 조합
* 커스텀 훅에서 데이터를 가져오고, UI 컴포넌트에 전달하여 상태를 표시합니다.
* 자식 Props 패턴으로 특정 UI를 부모에서 제어할 수 있도록 설계합니다.
4. 확장성과 재사용성을 위한 설계
* Render Props, Slot 패턴 등을 활용하여 더 유연한 UI 구성을 지원합니다.
* 특정 컴포넌트에서 사용하는 로직이나 이벤트를 쉽게 대체하거나 확장할 수 있도록 설계합니다.
1. 커스텀 훅에서 데이터와 로직 분리 - 훅 계층
* 상태 관리와 비즈니스 로직은 커스텀 훅에서 담당합니다
* map, filter, reduce 등의 메서드를 활용해 데이터를 변환하거나 조건에 따른 동작을 처리합니다
2. UI 컴포넌트를 합성 컴포넌트 패턴으로 설계 - 컴포넌트 계층
* UI 컴포넌트를 작은 단위로 나누고, Props를 활용해 데이터를 전달받아 렌더링합니다
* UI와 로직 간의 의존성을 제거합니다
3. 부모 컴포넌트에서 데이터와 UI 조합 - 컴포넌트 계층
* 커스텀 훅에서 데이터를 가져오고, UI 컴포넌트에 전달하여 상태를 표시합니다
* 자식 Props 패턴으로 특정 UI를 부모에서 제어할 수 있도록 설계합니다
4. 확장성과 재사용성을 위한 설계 - 훅 및 계산 함수 계층
* Render Props, Slot 패턴 등을 활용하여 더 유연한 UI 구성을 지원합니다
* 특정 컴포넌트에서 사용하는 로직이나 이벤트를 쉽게 대체하거나 확장할 수 있도록 설계합니다

위 설계로 얻는 리팩토링 결과의 장점은
* 관심사의 분리: 데이터 관리, 로직, UI가 명확히 분리되어 유지보수가 용이합니다.
* 유연성: 자식 Props 패턴과 합성 컴포넌트로 UI 구성을 유연하게 제어할 수 있습니다.
* 재사용성: 커스텀 훅과 컴포넌트가 독립적으로 설계되어 다양한 컨텍스트에서 재사용 가능합니다.
* 테스트 용이성: 상태 관리와 로직, UI를 독립적으로 테스트할 수 있습니다.
* 관심사의 분리: 데이터 관리, 로직, UI가 명확히 분리되어 유지보수가 용이하다
* 유연성: 자식 Props 패턴과 합성 컴포넌트로 UI 구성을 유연하게 제어할 수 있다
* 재사용성: 커스텀 훅과 컴포넌트가 독립적으로 설계되어 다양한 컨텍스트에서 재사용 가능하다
* 테스트 용이성: 상태 관리와 로직, UI를 독립적으로 테스트할 수 있다

#### 이제 가장 먼저 커스텀 훅 로직을 만들어보자

Expand Down
163 changes: 152 additions & 11 deletions src/advanced/__tests__/advanced.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { useState } from "react";
import { describe, expect, test } from 'vitest';
import { act, fireEvent, render, screen, within } from '@testing-library/react';
import { act, fireEvent, render, screen, within, renderHook } from '@testing-library/react';
import { CartPage } from '../../refactoring/components/CartPage';
import { AdminPage } from "../../refactoring/components/AdminPage";
import { Coupon, Product } from '../../types';
import { Coupon, Product, CartItem } from '../../types';
import * as discountUtils from "../../refactoring/utils/discount";
import { useAdmin } from "../../refactoring/hooks/useAdmin";

const mockProducts: Product[] = [
{
Expand Down Expand Up @@ -232,13 +234,152 @@ describe('advanced > ', () => {
})

describe('자유롭게 작성해보세요.', () => {
test('새로운 유틸 함수를 만든 후에 테스트 코드를 작성해서 실행해보세요', () => {
expect(true).toBe(true);
})

test('새로운 hook 함수를 만든 후에 테스트 코드를 작성해서 실행해보세요', () => {
expect(true).toBe(true);
})
})
})
describe("discountUtils", () => {
describe("getMaxDiscount", () => {
test("최대 할인율 반환하기", () => {
const discounts = mockProducts.flatMap(product => product.discounts)
const getMaxDiscount = discountUtils.getMaxDiscount(discounts);
expect(getMaxDiscount).toBe(0.2);
});
});

describe("getAppliedDiscount", () => {
const testProduct: Product = {
id: "1",
name: "Test Case",
price: 100,
stock: 10,
discounts: [
{ quantity: 2, rate: 0.1 },
{ quantity: 5, rate: 0.5 },
],
};

test("상황에 맞는 할인율 반환하기", () => {
const firstCase: CartItem = { product: testProduct, quantity: 1 };
const secondCase: CartItem = { product: testProduct, quantity: 5 };

expect(discountUtils.getAppliedDiscount(firstCase)).toBe(0);
expect(discountUtils.getAppliedDiscount(secondCase)).toBe(0.5);
});
});
});

describe("useAdmin", () => {
describe("handleAddCoupon", () => {
test("쿠폰이 newCoupon에 잘 초기화(추가) 하기", () => {
// 훅을 사용하여 상태와 메서드에 접근
const { result } = renderHook(() => useAdmin());
const couponValue: Coupon = {
name: "New Coupon",
code: "NEWCODE",
discountType: "amount",
discountValue: 5000,
};
let couponAdded = null;
const onCouponAdd = (coupon: Coupon) => {
couponAdded = coupon;
};

act(() => {
result.current.setNewCoupon(couponValue);
});
// 비동기 때문인가 따로 해야하는듯 하다
act(() => {
result.current.handleAddCoupon(onCouponAdd);
});

// `onCouponAdd`가 쿠폰을 정상적으로 받았는지 확인
expect(couponAdded).toEqual(couponValue);

// `newCoupon` 상태가 초기화되었는지 확인
expect(result.current.newCoupon).toEqual({
name: '',
code: '',
discountType: 'percentage',
discountValue: 0
});
});
});

describe("handleProductNameUpdate", () => {
test("상품 이름을 업데이트하기", () => {
const { result } = renderHook(() => useAdmin());

const product: Product = {
id: "1",
name: "Old Product",
price: 100,
stock: 10,
discounts: []
};

// handleEditProduct로 업데이트할 상품을 수정
act(() => {
result.current.handleEditProduct(product);
});

// 이름 업데이트
act(() => {
result.current.handleProductNameUpdate("1", "New Product");
});

// 이름이 업데이트되었는지 확인
expect(result.current.editingProduct?.name).toBe("New Product");
});
});

describe("handleAddNewProduct", () => {
test("새로운 상품을 추가하기", () => {
const { result } = renderHook(() => useAdmin());

const newProduct = { name: "New Product", price: 100, stock: 10, discounts: [] };

// newProduct 값을 설정
act(() => {
result.current.setNewProduct(newProduct);
});

// handleAddNewProduct 실행
act(() => {
result.current.handleAddNewProduct(() => {});
});

// 상태가 초기화되었는지 확인
expect(result.current.newProduct).toEqual({
name: '',
price: 0,
stock: 0,
discounts: []
});
});
});

describe("toggleProductAccordion", () => {
test("특정 제품의 accordion을 토글하기", () => {
const { result } = renderHook(() => useAdmin());

// 초기 상태에서 토글이 열린 제품이 없는지 확인
expect(result.current.openProductIds.size).toBe(0);

// product 의 id 가 1인 경우가 케이스
act(() => {
result.current.toggleProductAccordion("1");
});

// id 가 1 인 product 가 토글되었는지 확인
expect(result.current.openProductIds.size).toBe(1);
expect(result.current.openProductIds.has("1")).toBe(true);

// id 가 1 인 accordion 의 토글을 닫기
act(() => {
result.current.toggleProductAccordion("1");
});

// id 가 1 인 accordion 의 토글이 닫혔는지 확인
expect(result.current.openProductIds.size).toBe(0);
});
});
});
});
});
Loading