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

Test/#2 server chat module 테스트 코드 추가 #5

Merged
merged 11 commits into from
Jan 9, 2025
Merged
Changes from 1 commit
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
89 changes: 85 additions & 4 deletions server/src/chat/chat.gateway.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,99 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChatGateway } from './chat.gateway';
import { ChatService } from './chat.service';
import { BadRequestException, PlayerNotFoundException, RoomNotFoundException } from 'src/exceptions/game.exception';
import { Socket } from 'socket.io';

describe('ChatGateway', () => {
let gateway: ChatGateway;
let mockSocket: Partial<Socket>;

const mockChatService = {
existsRoom: jest.fn(),
existsPlayer: jest.fn(),
sendMessage: jest.fn(),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChatGateway],
providers: [ChatGateway, { provide: ChatService, useValue: mockChatService }],
}).compile();

gateway = module.get<ChatGateway>(ChatGateway);
gateway = module.get(ChatGateway);

/**
* as unknown as 를 이용해 타입을 먼저 unknown으로 바꾼 다음,
* 원하는 타입에 type assertion을 한다.
*/
mockSocket = {
handshake: { auth: { roomId: 'room1', playerId: 'player1' } },
data: {},
join: jest.fn(),
to: jest.fn().mockReturnThis(),
emit: jest.fn(),
} as unknown as Socket;
});

afterEach(() => {
jest.clearAllMocks();
});

describe('handleConnection 테스트', () => {
it('roomId가 null일 때 BadRequestException을 발생', () => {
mockSocket.handshake.auth = { roomId: null };

expect(() => gateway.handleConnection(mockSocket as Socket)).toThrow(BadRequestException);
Copy link
Collaborator

Choose a reason for hiding this comment

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

저처럼 any를 쓰는 것보다는 괜찮아보이지만 이렇게 모든 mockSocket에 대해서 다시 as Socket을 붙여야 하니... 정말 뭔가뭔가... 아쉽네요

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

맞아요.. 이거는 좀 아쉬운 거 같아요. 더 좋은 방법을 찾으면 업데이트할게요!

});

it('playerId가 null일 때 BadRequestException을 발생', () => {
mockSocket.handshake.auth = { playerId: null };

expect(() => gateway.handleConnection(mockSocket as Socket)).toThrow(BadRequestException);
});

it('room이 존재하지 않을 때 RoomNotFoundException을 발생', () => {
mockChatService.existsRoom.mockReturnValue(false);

expect(() => gateway.handleConnection(mockSocket as Socket)).toThrow(RoomNotFoundException);
expect(mockChatService.existsRoom).toHaveBeenCalled();
});

it('플레이어가 룸에 존재하지 않을 때 PlayerNotFoundException을 발생', () => {
mockChatService.existsRoom.mockReturnValue(true);
mockChatService.existsPlayer.mockReturnValue(false);

expect(() => gateway.handleConnection(mockSocket as Socket)).toThrow(PlayerNotFoundException);
expect(mockChatService.existsPlayer).toHaveBeenCalled();
});

it('플레이어와 방이 정상적으로 할당되어 있을 때', () => {
mockChatService.existsRoom.mockReturnValue(true);
mockChatService.existsPlayer.mockReturnValue(true);

gateway.handleConnection(mockSocket as Socket);

expect(mockSocket.join).toHaveBeenCalled();
expect(mockSocket.data).toEqual({ roomId: 'room1', playerId: 'player1' });
});
});

it('should be defined', () => {
expect(gateway).toBeDefined();
describe('handleSendMessage 테스트', () => {
it('데이터가 없을 때 BadRequestException을 발생', async () => {
mockSocket.data = {};

await expect(gateway.handleSendMessage(mockSocket as Socket, { message: 'hello world' })).rejects.toThrow(
BadRequestException,
);
});

it('정상적으로 메시지를 발신할 수 있을 때', async () => {
mockSocket.data = { roomId: 'room1', playerId: 'player1' };
mockChatService.sendMessage.mockResolvedValue({ message: 'hello world', sender: 'player1' });

await gateway.handleSendMessage(mockSocket as Socket, { message: 'hello world' });

expect(mockChatService.sendMessage).toHaveBeenCalled();
expect(mockSocket.to('room1').emit).toHaveBeenCalled();
});
});
});