Skip to content

Commit

Permalink
[BE#214] categories create, getUserById 테스트 코드 작성
Browse files Browse the repository at this point in the history
  • Loading branch information
yeongbinim authored Nov 30, 2023
1 parent e5341a0 commit ce4e32c
Show file tree
Hide file tree
Showing 17 changed files with 233 additions and 16 deletions.
3 changes: 3 additions & 0 deletions BE/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/$1"
},
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
Expand Down
126 changes: 125 additions & 1 deletion BE/src/categories/categories.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,58 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CategoriesService } from './categories.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Categories } from './categories.entity';
import categoriesData from '../../test/mock-table/categories.json';
import usersData from '../../test/mock-table/users.json';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { UsersModel } from 'src/users/entity/users.entity';
import { UsersService } from 'src/users/users.service';

class MockCategoriesRepository {
private data = categoriesData;
create(entity: object): object {
return {
id: this.data.length + 1,
...entity,
};
}

save(entity: object): Promise<object> {
return Promise.resolve(entity);
}

find({ where: { user_id } }): Promise<object> {
const categories = this.data.filter(
(category) => category.user_id === user_id.id,
);
return Promise.resolve(categories);
}
}

class MockUsersService {
private data: UsersModel[] = usersData as UsersModel[];
findUserById(user_id: number): Promise<object> {
const user = this.data.find((user) => user.id === user_id);
return Promise.resolve(user);
}
}

describe('CategoriesService', () => {
let service: CategoriesService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CategoriesService],
providers: [
CategoriesService,
{
provide: getRepositoryToken(Categories),
useClass: MockCategoriesRepository,
},
{
provide: UsersService,
useClass: MockUsersService,
},
],
}).compile();

service = module.get<CategoriesService>(CategoriesService);
Expand All @@ -15,4 +61,82 @@ describe('CategoriesService', () => {
it('should be defined', () => {
expect(service).toBeDefined();
});

describe('.create()', () => {
const normalData = { name: 'Test Category', color_code: 'FFFFFFFF' };
it('유효한 데이터로 카테고리를 성공적으로 생성해야 한다', async () => {
const userId = 1;
const result = await service.create(userId, normalData);
expect(result).toStrictEqual({
category_id: 3,
name: normalData.name,
color_code: normalData.color_code,
});
});
it('존재하지 않는 유저 ID가 주어지면 오류를 발생시켜야 한다', async () => {
const userId = 100;
expect(service.create(userId, normalData)).rejects.toThrow(
NotFoundException,
);
});
it('유효하지 않은 파라미터에 대해 오류를 발생시켜야 한다', async () => {
const userId = 1;
const nullUserId = null;
const nullData = null;
expect(service.create(nullUserId, nullData)).rejects.toThrow(
BadRequestException,
);
expect(service.create(userId, nullData)).rejects.toThrow(
BadRequestException,
);
expect(service.create(nullUserId, normalData)).rejects.toThrow(
BadRequestException,
);
});
});

describe('.findByUserId()', () => {
const existUserId = 1;
it('존재하는 유저 ID가 주어지면 카테고리들을 조회할 수 있어야 한다', async () => {
const result = await service.findByUserId(existUserId);
expect(result).toStrictEqual([
{ category_id: 1, name: '백준', color_code: 'FFFFFF' },
{ category_id: 2, name: '과학', color_code: 'BBBBBB' },
]);
});

it('카테고리가 없는 유저도 빈 배열을 줘야 한다', async () => {
const emptyCatgoryUserId = 2;
const result = await service.findByUserId(emptyCatgoryUserId);
expect(result).toStrictEqual([]);
});
it('존재하지 않는 유저 ID가 주어지면 오류를 발생시켜야 한다', () => {
const userId = 100;
expect(service.findByUserId(userId)).rejects.toThrow(NotFoundException);
});
it('유효하지 않은 파라미터에 대해 오류를 발생시켜야 한다', () => {
const nullUserId = null;
expect(service.findByUserId(nullUserId)).rejects.toThrow(
BadRequestException,
);
});
});

describe('.update()', () => {
it.todo('');
it.todo('');
it.todo('');
it.todo('');
it.todo('');
});
/**
* async update(
user_id: number,
categoriesData: CategoryUpdateDto,
id: number,
)
*/
// update Method

// remove Method
});
30 changes: 26 additions & 4 deletions BE/src/categories/categories.service.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,57 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Categories } from './categories.entity';
import { CategoryCreateDto } from './dto/request/create-categories.dto';
import { CategoryUpdateDto } from './dto/request/update-categories.dto';
import { CategoryDto } from './dto/response/category.dto';
import { UsersModel } from 'src/users/entity/users.entity';
import { UsersService } from 'src/users/users.service';

@Injectable()
export class CategoriesService {
constructor(
@InjectRepository(Categories)
private categoriesRepository: Repository<Categories>,
private usersService: UsersService,
) {}

async create(
user_id: number,
categoriesData: CategoryCreateDto,
): Promise<CategoryDto> {
const user = { id: user_id } as UsersModel;
if (!user_id || !categoriesData) {
throw new BadRequestException('인자의 형식이 잘못되었습니다.');
}
const user = await this.usersService.findUserById(user_id);
if (!user) {
throw new NotFoundException('해당 id의 유저가 존재하지 않습니다.');
}

const category = this.categoriesRepository.create({
...categoriesData,
user_id: user,
});

const savedCategory = await this.categoriesRepository.save(category);
return this.entityToDto(savedCategory);
}

async findByUserId(user_id: number): Promise<CategoryDto[]> {
if (!user_id) {
throw new BadRequestException('인자의 형식이 잘못되었습니다.');
}

const user = await this.usersService.findUserById(user_id);
if (!user) {
throw new NotFoundException('해당 id의 유저가 존재하지 않습니다.');
}

const categories = await this.categoriesRepository.find({
where: { user_id: { id: user_id } },
where: { user_id: { id: user.id } },
relations: ['user_id'],
});
const categoryDto = categories.map((category) => {
Expand Down
2 changes: 1 addition & 1 deletion BE/src/common/logging.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as winston from 'winston';
import winston from 'winston';

const customFormat = winston.format.printf(
({ level, message, timestamp, context }) => {
Expand Down
4 changes: 2 additions & 2 deletions BE/src/common/multer.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as path from 'path';
import path from 'path';
import { BadRequestException } from '@nestjs/common';
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';
import * as multer from 'multer';
import multer from 'multer';

export const multerConfig = (): MulterOptions => {
const storage = multer.memoryStorage();
Expand Down
4 changes: 2 additions & 2 deletions BE/src/common/s3.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import * as sharp from 'sharp';
import sharp from 'sharp';
import { v4 as uuidv4 } from 'uuid';
import * as path from 'path';
import path from 'path';

@Injectable()
export class S3Service {
Expand Down
2 changes: 1 addition & 1 deletion BE/src/common/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as path from 'path';
import path from 'path';

export function transformDate(date: Date): string {
const year = date.getFullYear();
Expand Down
2 changes: 1 addition & 1 deletion BE/src/mates/mates.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { getImageUrl } from 'src/common/utils';
import { ConfigService } from '@nestjs/config';
import { ENV } from 'src/common/const/env-keys.const';
import { StudyLogsService } from 'src/study-logs/study-logs.service';
import * as moment from 'moment';
import moment from 'moment';

@Injectable()
export class MatesService {
Expand Down
2 changes: 1 addition & 1 deletion BE/src/study-logs/study-logs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Categories } from 'src/categories/categories.entity';
import { StudyLogsDto } from './dto/response/study-logs.dto';
import { transformDate } from 'src/common/utils';
import { RedisService } from 'src/common/redis.service';
import * as moment from 'moment';
import moment from 'moment';

@Injectable()
export class StudyLogsService {
Expand Down
6 changes: 6 additions & 0 deletions BE/src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ export class UsersService {
where: { email },
});

if (!selectedUser) {
throw new BadRequestException('해당 유저가 존재하지 않습니다.');
}
return selectedUser;
}

Expand All @@ -95,6 +98,9 @@ export class UsersService {
where: { id: user_id },
});

if (!selectedUser) {
throw new BadRequestException('해당 유저가 존재하지 않습니다.');
}
return selectedUser;
}

Expand Down
2 changes: 1 addition & 1 deletion BE/test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import request from 'supertest';
import { AppModule } from '../src/app.module';

describe('AppController (e2e)', () => {
Expand Down
14 changes: 14 additions & 0 deletions BE/test/mock-table/categories.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"id": 1,
"name": "백준",
"color_code": "FFFFFF",
"user_id": 1
},
{
"id": 2,
"name": "과학",
"color_code": "BBBBBB",
"user_id": 1
}
]
7 changes: 7 additions & 0 deletions BE/test/mock-table/mates.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{
"id": 1,
"follower_id": 1,
"following_id": 2
}
]
Empty file.
20 changes: 20 additions & 0 deletions BE/test/mock-table/study-logs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[
{
"id": 1,
"date": "2023-11-29",
"created_at": "2023-11-29 12:11:12",
"type": "finish",
"learning_time": 315,
"user_id": 1,
"category_id": null
},
{
"id": 2,
"date": "2023-11-29",
"created_at": "2023-11-29 15:11:12",
"type": "finish",
"learning_time": 512,
"user_id": 1,
"category_id": 1
}
]
16 changes: 16 additions & 0 deletions BE/test/mock-table/users.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[
{
"id": 1,
"nickname": "어린콩",
"auth_type": "google",
"email": "[email protected]",
"image_url": null
},
{
"id": 2,
"nickname": "어린콩2",
"auth_type": "google",
"email": "[email protected]",
"image_url": null
}
]
9 changes: 7 additions & 2 deletions BE/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@
"target": "ES2021",
"sourceMap": true,
"outDir": "dist",
"baseUrl": "",
"baseUrl": ".",
"paths": {
"src/*": ["src/*"]
},
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
"noFallthroughCasesInSwitch": false,
"resolveJsonModule": true,
"esModuleInterop": true
}
}

0 comments on commit ce4e32c

Please sign in to comment.