From d7078bb6cb60b626012fd55ffa68b802b51ac364 Mon Sep 17 00:00:00 2001 From: Khaled FERJANI Date: Fri, 31 Jan 2025 10:58:14 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AA=20chore:=20add=20SMS=20Service=20A?= =?UTF-8?q?PI=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/utils/sms-service.test.ts | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 packages/matrix-identity-server/src/utils/sms-service.test.ts diff --git a/packages/matrix-identity-server/src/utils/sms-service.test.ts b/packages/matrix-identity-server/src/utils/sms-service.test.ts new file mode 100644 index 00000000..fded49ca --- /dev/null +++ b/packages/matrix-identity-server/src/utils/sms-service.test.ts @@ -0,0 +1,85 @@ +import { TwakeLogger } from '@twake/logger' +import type { Config } from '../types' +import { SmsService } from './sms-service' + +const loggerMock = { + info: jest.fn(), + error: jest.fn() +} + +const mockConfig = { + sms_api_key: 'test_key', + sms_api_login: 'test_secret', + sms_api_url: 'http://localhost/sms/api' +} + +describe('the SMS service', () => { + const smsService = new SmsService( + mockConfig as Config, + loggerMock as unknown as TwakeLogger + ) + + describe('the send method', () => { + it('should send a SMS', async () => { + global.fetch = jest.fn().mockImplementation(() => { + return Promise.resolve({ + json: () => Promise.resolve({ success: true }), + status: 200 + }) + }) + + await smsService.send('test', 'test') + expect(loggerMock.error).not.toHaveBeenCalled() + }) + + it('should log an error when failed to send SMS', async () => { + global.fetch = jest.fn().mockImplementation(() => { + return Promise.resolve({ + json: () => Promise.resolve({}), + status: 401 + }) + }) + + await smsService.send('test', 'test') + + expect(loggerMock.error).toHaveBeenCalledWith( + 'Failed to send SMS', + expect.anything() + ) + }) + + it('should throw an error when instantiated with missing config', async () => { + expect( + () => new SmsService({} as Config, loggerMock as unknown as TwakeLogger) + ).toThrow('Missing SMS API configuration') + }) + + it('should call the API endpoint with correct parameters', async () => { + global.fetch = jest.fn().mockImplementation(() => { + return Promise.resolve({ + json: () => Promise.resolve({ success: true }), + status: 200 + }) + }) + + await smsService.send('+330744556688', 'test sms') + + expect(fetch).toHaveBeenCalledWith( + 'http://localhost/sms/api/sms-campaign/send', + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'api-login': 'test_secret', + 'api-key': 'test_key' + }, + body: JSON.stringify({ + to: '+330744556688', + body: 'test sms', + from: 'Twake Chat' + }) + } + ) + }) + }) +})