diff --git a/apps/alias-server/test/mocks/telegramBotMock.js b/apps/alias-server/test/mocks/telegramBotMock.js new file mode 100644 index 000000000..1f5196bf3 --- /dev/null +++ b/apps/alias-server/test/mocks/telegramBotMock.js @@ -0,0 +1,31 @@ +// Copyright (c) 2023 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +'use strict'; + +/* Mock node-telegram-bot-api TelegramBot instance + * Supports sendMessage function + */ + +module.exports = { + MockTelegramBot: class { + constructor() { + // Use self since it is not a reserved term in js + // Can access self from inside a method and still get the class + const self = this; + self.messageSent = false; + self.errors = {}; + self.sendMessage = async function (channelId, msg, options) { + if (!self.errors.sendMessage) { + self.messageSent = true; + return { success: true, channelId, msg, options }; + } + throw new Error(self.errors.sendMessage); + }; + self.setExpectedError = function (method, error) { + self.errors[method] = error; + }; + } + }, + mockChannelId: '-1001999999999', +}; diff --git a/apps/alias-server/test/telegramTests.js b/apps/alias-server/test/telegramTests.js new file mode 100644 index 000000000..043edba05 --- /dev/null +++ b/apps/alias-server/test/telegramTests.js @@ -0,0 +1,56 @@ +// Copyright (c) 2023 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +'use strict'; +const assert = require('assert'); +const { MockTelegramBot, mockChannelId } = require('./mocks/telegramBotMock'); +const { returnTelegramBotSendMessagePromise } = require('../src/telegram'); + +describe('alias-server telegram.js', async function () { + const testTgMsgOptions = { + parse_mode: 'HTML', + disable_web_page_preview: true, + }; + let testTelegramBot; + beforeEach(async () => { + // Initialize db before each unit test + testTelegramBot = new MockTelegramBot(); + }); + it('returnTelegramBotSendMessagePromise constructs promises to send a telegram message', async function () { + // Create array of promises + const tgMsgPromises = []; + const testMsgOne = 'Test Message One'; + const testMsgTwo = 'Test Message Two'; + tgMsgPromises.push( + returnTelegramBotSendMessagePromise( + testTelegramBot, + mockChannelId, + testMsgOne, + testTgMsgOptions, + ), + ); + tgMsgPromises.push( + returnTelegramBotSendMessagePromise( + testTelegramBot, + mockChannelId, + testMsgTwo, + testTgMsgOptions, + ), + ); + const testMsgSentResult = await Promise.all(tgMsgPromises); + assert.deepEqual(testMsgSentResult, [ + { + channelId: mockChannelId, + msg: testMsgOne, + options: testTgMsgOptions, + success: true, + }, + { + channelId: mockChannelId, + msg: testMsgTwo, + options: testTgMsgOptions, + success: true, + }, + ]); + }); +});