From 15b7108be4413869f2718a1b24763ac28e61218d Mon Sep 17 00:00:00 2001 From: Marius Begby Date: Tue, 13 Feb 2024 11:10:37 +0100 Subject: [PATCH] experiment with adding unit tests for command handler --- src/tests/handlers/commandHandler.test.ts | 61 +++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/tests/handlers/commandHandler.test.ts diff --git a/src/tests/handlers/commandHandler.test.ts b/src/tests/handlers/commandHandler.test.ts new file mode 100644 index 0000000..0daff51 --- /dev/null +++ b/src/tests/handlers/commandHandler.test.ts @@ -0,0 +1,61 @@ +import { handleCommand } from '../../handlers/interactionCommandHandler'; +import { ChatInputCommandInteraction } from 'discord.js'; +import { BaseSlashCommandInteraction } from '../../common/classes/interactions'; +import { ExtendedClient } from '../../types/clientTypes'; +import { checkChannelPermissionViewable } from '../../common/validation/permissionValidator'; +import loggerModule from '../../common/services/logger'; + +jest.mock('../../common/validation/permissionValidator'); +jest.mock('../../common/services/logger', () => ({ + child: jest.fn().mockReturnThis(), + debug: jest.fn(), + warn: jest.fn() +})); + +describe('interactionCommandHandler', () => { + let mockInteraction: ChatInputCommandInteraction; + let client: ExtendedClient; + let executionId: string; + let interactionIdentifier: string; + + beforeEach(() => { + mockInteraction = { + reply: jest.fn(), + commandName: 'testCommand' + } as unknown as ChatInputCommandInteraction; + + client = { + slashCommandInteractions: new Map() + } as unknown as ExtendedClient; + + executionId = '123'; + interactionIdentifier = 'testCommand'; + }); + + it('should handle command correctly when slash command is found', async () => { + const mockSlashCommand = { + execute: jest.fn() + } as unknown as BaseSlashCommandInteraction; + + client.slashCommandInteractions?.set(interactionIdentifier, mockSlashCommand); + + await handleCommand(mockInteraction, client, executionId, interactionIdentifier); + + expect(checkChannelPermissionViewable).toHaveBeenCalledWith({ interaction: mockInteraction, executionId }); + expect(mockSlashCommand.execute).toHaveBeenCalledWith({ interaction: mockInteraction, client, executionId }); + }); + + it('should handle command correctly when slash command is not found', async () => { + const loggerSpy = jest.spyOn( + loggerModule.child({ module: 'handler', name: 'interactionCommandHandler', executionId: executionId }), + 'warn' + ); + + await handleCommand(mockInteraction, client, executionId, interactionIdentifier); + + expect(checkChannelPermissionViewable).toHaveBeenCalledWith({ interaction: mockInteraction, executionId }); + expect(loggerSpy).toHaveBeenCalledWith( + `Interaction created but slash command '${interactionIdentifier}' was not found.` + ); + }); +});