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

[GWL-213] posts 테스트 코드 작성 및 리팩토링 #256

Merged
merged 3 commits into from
Dec 7, 2023
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
10 changes: 5 additions & 5 deletions BackEnd/src/common/common.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,16 @@ export class CommonService {
queryOptions: QueryOptions,
findManyOptions: FindManyOptions<T> = {},
) {
let queryBilder = repository.createQueryBuilder(queryOptions.mainAlias);
queryBilder = queryBilder.setFindOptions(findManyOptions);
let queryBuilder = repository.createQueryBuilder(queryOptions.mainAlias);
queryBuilder = queryBuilder.setFindOptions(findManyOptions);
if (queryOptions.join) {
queryOptions.join.forEach((value: JoinType) => {
queryBilder = queryBilder.leftJoin(value.joinColumn, value.joinAlias);
queryBuilder = queryBuilder.leftJoin(value.joinColumn, value.joinAlias);
});
}
if (queryOptions.select) {
queryBilder = queryBilder.select(queryOptions.select);
queryBuilder = queryBuilder.select(queryOptions.select);
}
return queryBilder;
return queryBuilder;
}
}
2 changes: 1 addition & 1 deletion BackEnd/src/posts/dto/get-posts-response.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class MetaDataDto {
count: number;
}

class PostsPaginateResDto {
export class PostsPaginateResDto {
@ApiProperty({ type: () => [PostDto] })
items: PostDto[];

Expand Down
2 changes: 1 addition & 1 deletion BackEnd/src/posts/dto/paginate-post.dto.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import {BasePaginationDto} from "../../common/dto/base-pagination.dto";
import { BasePaginationDto } from '../../common/dto/base-pagination.dto';

export class PaginatePostDto extends BasePaginationDto {}
133 changes: 133 additions & 0 deletions BackEnd/src/posts/mocks/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { UpdateResult } from 'typeorm';
import { Profile } from '../../profiles/entities/profiles.entity';
import { CreatePostDto } from '../dto/create-post.dto';
import { PostDto, PostsPaginateResDto } from '../dto/get-posts-response.dto';
import { PaginatePostDto } from '../dto/paginate-post.dto';
import { UpdatePostDto } from '../dto/update-post.dto';

export const postInfo: CreatePostDto = {
content: 'test content',
postUrl: 'naver.com',
recordId: 1,
};

export const updatePostInfo: UpdatePostDto = {
content: 'update content',
postUrl: 'google.com',
};

export const profile = {
publicId: 'XVZXC-ASFSA123-ASFSF',
nickname: 'testNickname',
} as Profile;

export const query: PaginatePostDto = {
where__id__less_then: 7,
order__createdAt: 'DESC',
take: 5,
};

export const post: PostDto = {
id: 5,
publicId: profile.publicId,
content: postInfo.content,
like: null,
createdAt: new Date('2023-12-04T05:14:15.879Z'),
updatedAt: new Date('2023-12-04T05:14:15.879Z'),
deletedAt: null,
postUrl: postInfo.postUrl,
record: {
id: postInfo.recordId,
workoutTime: 6000000,
distance: 100000,
calorie: 360,
avgHeartRate: 60,
minHeartRate: 120,
maxHeartRate: 180,
},
profile: {
nickname: profile.nickname,
},
};
export const updateResult: UpdateResult = {
generatedMaps: [],
raw: [],
affected: 1,
};

export const updatedPost: PostDto = {
id: 5,
publicId: profile.publicId,
content: updatePostInfo.content,
like: null,
createdAt: new Date('2023-12-04T05:14:15.879Z'),
updatedAt: new Date('2023-12-05T05:14:15.879Z'),
deletedAt: null,
postUrl: updatePostInfo.postUrl,
record: {
id: postInfo.recordId,
workoutTime: 6000000,
distance: 100000,
calorie: 360,
avgHeartRate: 60,
minHeartRate: 120,
maxHeartRate: 180,
},
profile: {
nickname: profile.nickname,
},
};

export const posts: PostsPaginateResDto = {
items: [
{
id: 6,
publicId: profile.publicId,
content: '안녕하세요 누구 누구 입니다.',
like: null,
createdAt: new Date('2023-12-04T05:14:15.879Z'),
updatedAt: new Date('2023-12-04T05:14:15.879Z'),
deletedAt: null,
postUrl: 'https://www.naver.com',
record: {
id: 2,
workoutTime: 6000000,
distance: 100000,
calorie: 360,
avgHeartRate: 60,
minHeartRate: 120,
maxHeartRate: 180,
},
profile: {
nickname: profile.nickname,
},
},
{
id: 5,
publicId: profile.publicId,
content: '수정한 내용입니다.',
like: null,
createdAt: new Date('2023-12-03T13:47:08.677Z'),
updatedAt: new Date('2023-12-04T12:44:44.000Z'),
deletedAt: null,
postUrl: 'google.com',
record: {
id: 1,
workoutTime: 100,
distance: 100,
calorie: 100,
avgHeartRate: 100,
minHeartRate: 100,
maxHeartRate: 100,
},
profile: {
nickname: profile.nickname,
},
},
],
metaData: {
lastItemId: 5,
isLastCursor: true,
count: 2,
},
};
101 changes: 101 additions & 0 deletions BackEnd/src/posts/posts.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';
import {
post,
postInfo,
posts,
profile,
query,
updatePostInfo,
updatedPost,
} from './mocks/mocks';
import { AuthService } from '../auth/auth.service';
import { ProfilesService } from '../profiles/profiles.service';

describe('postsController', () => {
let controller: PostsController;
let service: PostsService;

beforeEach(async () => {
const mockService = () => ({
createPost: jest.fn(),
paginatePosts: jest.fn(),
findOneById: jest.fn(),
paginateUserPosts: jest.fn(),
updatePost: jest.fn(),
deletePost: jest.fn(),
});

const module: TestingModule = await Test.createTestingModule({
providers: [
PostsController,
{
provide: PostsService,
useValue: mockService(),
},
{
provide: AuthService,
useValue: {},
},
{
provide: ProfilesService,
useValue: {},
},
],
}).compile();
controller = module.get<PostsController>(PostsController);
service = module.get<PostsService>(PostsService);
});

describe('createPost', () => {
it('유저가 입력한 정보로 post 생성', async () => {
jest.spyOn(service, 'createPost').mockResolvedValue(post);
const result = await controller.createPost(postInfo, profile);
expect(result).toEqual(post);
});
});

describe('getPosts', () => {
it('홈에 보여줄 게시글 요청', async () => {
jest.spyOn(service, 'paginatePosts').mockResolvedValue(posts);
const result = await controller.getPosts(query);
expect(result).toEqual(posts);
});
});

describe('getPostById', () => {
it('유저가 id의 해당하는 게시글을 요청', async () => {
jest.spyOn(service, 'findOneById').mockResolvedValue(post);
const result = await controller.getPostById(post.id);
expect(result).toEqual(post);
});
});

describe('getUserPosts', () => {
it('특정 유저의 게시글 요청', async () => {
jest.spyOn(service, 'paginateUserPosts').mockResolvedValue(posts);
const result = await controller.getUserPosts(profile.publicId, query);
expect(result).toEqual(posts);
});
});

describe('getMyPosts', () => {
it('내 게시글 요청', async () => {
jest.spyOn(service, 'paginateUserPosts').mockResolvedValue(posts);
const result = await controller.getMyPosts(profile, query);
expect(result).toEqual(posts);
});
});

describe('updateMyPost', () => {
it('내 게시글 수정 후 수정되었는지 확인하기', async () => {
jest.spyOn(service, 'updatePost').mockResolvedValue(updatedPost);
const result = await controller.updateMyPost(
updatedPost.id,
updatePostInfo,
);
expect(result).toEqual(updatedPost);
});
});
});
22 changes: 14 additions & 8 deletions BackEnd/src/posts/posts.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ import { CreatePostDto } from './dto/create-post.dto';
import { Profile } from '../profiles/entities/profiles.entity';
import { ProfileDeco } from '../profiles/decorator/profile.decorator';
import { PaginatePostDto } from './dto/paginate-post.dto';
import { GetPostsResponseDto } from './dto/get-posts-response.dto';
import {
GetPostsResponseDto,
PostDto,
PostsPaginateResDto,
} from './dto/get-posts-response.dto';
import { GetPostResponseDto } from './dto/get-create-update-post-response.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { DeletePostResponseDto } from './dto/delete-post-response.dto';
Expand All @@ -40,21 +44,23 @@ export class PostsController {
async createPost(
@Body() body: CreatePostDto,
@ProfileDeco() profile: Profile,
) {
return await this.postsService.createPost(body, profile);
): Promise<PostDto> {
return this.postsService.createPost(body, profile);
}

@Get()
@ApiOperation({ summary: '게시글 가져오기' })
@ApiCreatedResponse({ type: GetPostsResponseDto })
async getPosts(@Query() query: PaginatePostDto) {
async getPosts(
@Query() query: PaginatePostDto,
): Promise<PostsPaginateResDto> {
return this.postsService.paginatePosts(query);
}

@Get(':id')
@ApiOperation({ summary: '특정 게시글 가져오기' })
@ApiCreatedResponse({ type: GetPostResponseDto })
async getPostById(@Param('id', ParseIntPipe) id: number) {
async getPostById(@Param('id', ParseIntPipe) id: number): Promise<PostDto> {
return this.postsService.findOneById(id);
}

Expand All @@ -64,7 +70,7 @@ export class PostsController {
async getUserPosts(
@Param('publicId') publicId: string,
@Query() query: PaginatePostDto,
) {
): Promise<PostsPaginateResDto> {
return this.postsService.paginateUserPosts(publicId, query);
}

Expand All @@ -75,7 +81,7 @@ export class PostsController {
async getMyPosts(
@ProfileDeco() profile: Profile,
@Query() query: PaginatePostDto,
) {
): Promise<PostsPaginateResDto> {
return this.postsService.paginateUserPosts(profile.publicId, query);
}

Expand All @@ -86,7 +92,7 @@ export class PostsController {
async updateMyPost(
@Param('id', ParseIntPipe) id: number,
@Body() body: UpdatePostDto,
) {
): Promise<PostDto> {
return this.postsService.updatePost(id, body);
}

Expand Down
Loading
Loading