Skip to content

[25.03.09 / TASK-136] Feature - post repo order test, 레포 계층 테스팅과 CI 파이프라인 #20

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

Merged
merged 5 commits into from
Mar 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
60 changes: 60 additions & 0 deletions .github/workflows/test-ci.yaml

Choose a reason for hiding this comment

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

테스트에 대한 CI는 이번에 처음 접하게 되었는데, 전체적으로 잘 구성된 워크플로우 같아 배우고갑니다!
특히, matrix.node-version에 대해서 찾아본 결과 여러 Node.js 버전을 테스트하도록 활용하신 부분이 인상적이었습니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
name: Test CI

on:
workflow_dispatch:
push:
branches: ['main']
pull_request:
branches: ['main']

jobs:
build-and-test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20, 21, 22, 23]
fail-fast: false # 한 버전 실패 시 전체 중단 방지

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Set up Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}

- name: Enable Corepack
run: corepack enable

- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 9
run_install: false

- name: Get pnpm store directory
id: pnpm-cache
shell: bash
run: |
echo "store-path=$(pnpm store path)" >> $GITHUB_OUTPUT

- name: Setup pnpm cache
uses: actions/cache@v4
with:
path: ${{ steps.pnpm-cache.outputs.store-path }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-

- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Run lint
run: pnpm run lint

- name: Run tests
run: pnpm run test

- name: Run build
run: pnpm run build
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Velog Dashboard Project

- 백엔드 API 서버
- Velog dashboard V2 백엔드, API 서버
- ***`node 20+`***

## Project Setup Guide

Expand Down
3 changes: 0 additions & 3 deletions src/__test__/sum.test.ts

This file was deleted.

145 changes: 145 additions & 0 deletions src/repositories/__test__/post.repository.test.ts

Choose a reason for hiding this comment

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

junit, pytest, 그리고 jest까지 사용되는 언어만 다를뿐 mocking, equal, greaterThan, throw까지 동작하는 방식은 비슷하다는 점이 인상깊은 것 같습니다!

기능적인 부분에 대한 질문은 아니지만, 테스트코드를 구현할 때 가장 중요하게 생각하시는 부분이 무엇인지 현우님만의 관점이 궁금합니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { Pool, QueryResult } from 'pg';
import { PostRepository } from '@/repositories/post.repository';
import { DBError } from '@/exception';

jest.mock('pg');

const mockPool: {
query: jest.Mock<Promise<QueryResult<Record<string, unknown>>>, unknown[]>;
} = {
query: jest.fn(),
};

describe('PostRepository', () => {
let repo: PostRepository;

beforeEach(() => {
repo = new PostRepository(mockPool as unknown as Pool);
});

describe('findPostsByUserId', () => {
it('사용자의 게시글과 nextCursor를 반환해야 한다', async () => {
const mockPosts = [
{ id: 1, post_released_at: '2025-03-01T00:00:00Z', daily_view_count: 10, daily_like_count: 5 },
{ id: 2, post_released_at: '2025-03-02T00:00:00Z', daily_view_count: 20, daily_like_count: 15 },
];

mockPool.query.mockResolvedValue({
rows: mockPosts,
rowCount: mockPosts.length,
command: '',
oid: 0,
fields: [],
} as QueryResult);

const result = await repo.findPostsByUserId(1, undefined, 'released_at', false);

expect(result.posts).toEqual(mockPosts);
expect(result).toHaveProperty('nextCursor');
});

it('정렬 순서를 보장해야 한다', async () => {
const mockPosts = [
{ id: 2, post_released_at: '2025-03-02T00:00:00Z', daily_view_count: 20, daily_like_count: 15 },
{ id: 1, post_released_at: '2025-03-01T00:00:00Z', daily_view_count: 10, daily_like_count: 5 },
];

mockPool.query.mockResolvedValue({
rows: mockPosts,
rowCount: mockPosts.length,
command: '',
oid: 0,
fields: [],
} as QueryResult);

const result = await repo.findPostsByUserId(1, undefined, 'released_at', false);
expect(result.posts).toEqual(mockPosts);
expect(result.posts[0].id).toBeGreaterThan(result.posts[1].id);
});
});

describe('getTotalPostCounts', () => {
it('사용자의 총 게시글 수를 반환해야 한다', async () => {
mockPool.query.mockResolvedValue({
rows: [{ count: '10' }],
rowCount: 1,
command: '',
oid: 0,
fields: [],
} as QueryResult);

const count = await repo.getTotalPostCounts(1);
expect(count).toBe(10);
});
});

describe('에러 발생 시 처리', () => {
it('쿼리 실행 중 에러가 발생하면 DBError를 던져야 한다', async () => {
mockPool.query.mockRejectedValue(new Error('DB connection failed'));

await expect(repo.findPostsByUserId(1)).rejects.toThrow(DBError);
await expect(repo.getTotalPostCounts(1)).rejects.toThrow(DBError);
});
});

describe('getYesterdayAndTodayViewLikeStats', () => {
it('어제와 오늘의 조회수 및 좋아요 수를 반환해야 한다', async () => {
const mockStats = {
daily_view_count: 20,
daily_like_count: 15,
yesterday_views: 10,
yesterday_likes: 8,
last_updated_date: '2025-03-08T00:00:00Z',
};

mockPool.query.mockResolvedValue({
rows: [mockStats],
rowCount: 1,
command: '',
oid: 0,
fields: [],
} as QueryResult);

const result = await repo.getYesterdayAndTodayViewLikeStats(1);
expect(result).toEqual(mockStats);
});
});

describe('findPostByPostId', () => {
it('특정 post ID에 대한 통계를 반환해야 한다', async () => {
const mockStats = [
{ date: '2025-03-08T00:00:00Z', daily_view_count: 50, daily_like_count: 30 },
];

mockPool.query.mockResolvedValue({
rows: mockStats,
rowCount: mockStats.length,
command: '',
oid: 0,
fields: [],
} as QueryResult);

const result = await repo.findPostByPostId(1);
expect(result).toEqual(mockStats);
});
});

describe('findPostByPostUUID', () => {
it('특정 post UUID에 대한 통계를 반환해야 한다', async () => {
const mockStats = [
{ date: '2025-03-08T00:00:00Z', daily_view_count: 50, daily_like_count: 30 },
];

mockPool.query.mockResolvedValue({
rows: mockStats,
rowCount: mockStats.length,
command: '',
oid: 0,
fields: [],
} as QueryResult);

const result = await repo.findPostByPostUUID('uuid-1234', '2025-03-01', '2025-03-08');
expect(result).toEqual(mockStats);
});
});
});
1 change: 1 addition & 0 deletions src/repositories/post.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ export class PostRepository {
pds.daily_like_count
FROM posts_postdailystatistics pds
WHERE pds.post_id = $1
ORDER BY pds.date ASC
`;

const values: (number | string)[] = [postId];
Expand Down