Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test: cover message send endpoints, catalog, label delegation, and session lifecycle edges
Yudhi Armyndharis6b692076e792
diff --git a/src/modules/catalog/catalog.controller.spec.ts b/src/modules/catalog/catalog.controller.spec.tsnew file mode 100644index 000000000..e79ecec0c--- /dev/null+++ b/src/modules/catalog/catalog.controller.spec.ts@@ -0,0 +1,64 @@+import { CatalogController } from './catalog.controller';+import type { CatalogService } from './catalog.service';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import type { Catalog, PaginatedProducts, Product } from '../../engine/interfaces/whatsapp-engine.interface';++/**+ * The controller is a thin map from route params/DTOs onto CatalogService's positional arguments.+ * What is worth pinning here is the wiring itself (which field lands in which argument slot) and+ * that the deliberate 501 from send-catalog reaches the caller instead of being swallowed.+ */+describe('CatalogController', () => {+ const service = {+ getCatalog: jest.fn(),+ getProducts: jest.fn(),+ getProduct: jest.fn(),+ sendProduct: jest.fn(),+ sendCatalog: jest.fn(),+ };+ const controller = new CatalogController(service as unknown as CatalogService);++ beforeEach(() => jest.clearAllMocks());++ it('getCatalog forwards the session id', async () => {+ const catalog = { id: 'cat-1' } as Catalog;+ service.getCatalog.mockResolvedValue(catalog);++ await expect(controller.getCatalog('s1')).resolves.toBe(catalog);+ expect(service.getCatalog).toHaveBeenCalledWith('s1');+ });++ it('getProducts forwards the parsed page window, not the query object', async () => {+ const page = { products: [] } as PaginatedProducts;+ service.getProducts.mockResolvedValue(page);++ await expect(controller.getProducts('s1', { page: 2, limit: 10 })).resolves.toBe(page);+ expect(service.getProducts).toHaveBeenCalledWith('s1', 2, 10);+ });++ it('getProduct forwards the product id from the route', async () => {+ const product = { id: 'prod-1' } as Product;+ service.getProduct.mockResolvedValue(product);++ await expect(controller.getProduct('s1', 'prod-1')).resolves.toBe(product);+ expect(service.getProduct).toHaveBeenCalledWith('s1', 'prod-1');+ });++ it('sendProduct maps the DTO onto the service’s positional arguments', async () => {+ const sent = { id: 'wamid.product', timestamp: 1_706_868_000 };+ service.sendProduct.mockResolvedValue(sent);++ const dto = { chatId: '[email protected]', productId: 'prod-1', body: 'Back in stock!' };+ await expect(controller.sendProduct('s1', dto)).resolves.toBe(sent);+ expect(service.sendProduct).toHaveBeenCalledWith('s1', '[email protected]', 'prod-1', 'Back in stock!');+ });++ it('sendCatalog lets the deliberate 501 through — no engine can send catalog links', async () => {+ const unsupported = new EngineNotSupportedError('sendCatalog');+ service.sendCatalog.mockRejectedValue(unsupported);++ await expect(controller.sendCatalog('s1', { chatId: '[email protected]', body: 'hi' })).rejects.toBe(unsupported);+ expect(unsupported.getStatus()).toBe(501);+ expect(service.sendCatalog).toHaveBeenCalledWith('s1', '[email protected]', 'hi');+ });+});diff --git a/src/modules/catalog/catalog.service.spec.ts b/src/modules/catalog/catalog.service.spec.tsnew file mode 100644index 000000000..ef045cc6b--- /dev/null+++ b/src/modules/catalog/catalog.service.spec.ts@@ -0,0 +1,139 @@+import { NotFoundException, NotImplementedException } from '@nestjs/common';+import { CatalogService } from './catalog.service';+import { EngineRegistry } from '../../engine/engine-registry.service';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import type { SendPacingService } from '../message/send-pacing.service';+import type {+ IWhatsAppEngine,+ Catalog,+ Product,+ PaginatedProducts,+ MessageResult,+} from '../../engine/interfaces/whatsapp-engine.interface';++const catalog: Catalog = { id: 'cat-1', name: 'Toko Kue', productCount: 2, url: 'https://wa.me/c/628123' };+const product: Product = {+ id: 'prod-1',+ name: 'Brownies',+ price: 25000,+ currency: 'IDR',+ priceFormatted: 'Rp25.000',+ url: 'https://wa.me/p/prod-1/628123',+ isAvailable: true,+};+const page: PaginatedProducts = { products: [product], pagination: { page: 1, limit: 20, total: 1, totalPages: 1 } };+const sent: MessageResult = { id: 'wamid.product', timestamp: 1_706_868_000 };++describe('CatalogService', () => {+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined, pacing?: { assertSendAllowed: jest.Mock }) => {+ const engines = new EngineRegistry();+ if (engine) engines.set('s1', engine as IWhatsAppEngine);+ const sendPacing = pacing ?? { assertSendAllowed: jest.fn().mockResolvedValue(undefined) };+ return { svc: new CatalogService(engines, sendPacing as unknown as SendPacingService), pacing: sendPacing };+ };++ describe('catalog reads', () => {+ it.each(['getCatalog', 'getProducts', 'getProduct'] as const)(+ 'rejects with 404 for %s when the session is not started',+ async method => {+ const { svc } = makeService(undefined);+ const promise =+ method === 'getProduct'+ ? svc.getProduct('s1', 'prod-1')+ : method === 'getProducts'+ ? svc.getProducts('s1')+ : svc.getCatalog('s1');+ await expect(promise).rejects.toBeInstanceOf(NotFoundException);+ },+ );++ it('delegates getCatalog to the engine and returns its answer (null when the account has none)', async () => {+ const getCatalog = jest.fn().mockResolvedValue(catalog);+ const { svc } = makeService({ getCatalog });+ await expect(svc.getCatalog('s1')).resolves.toBe(catalog);++ getCatalog.mockResolvedValue(null);+ await expect(svc.getCatalog('s1')).resolves.toBeNull();+ });++ it('delegates getProducts with the requested page window', async () => {+ const getProducts = jest.fn().mockResolvedValue(page);+ const { svc } = makeService({ getProducts });+ await expect(svc.getProducts('s1', 3, 50)).resolves.toBe(page);+ expect(getProducts).toHaveBeenCalledWith({ page: 3, limit: 50 });+ });++ it('defaults getProducts to the first page of 20', async () => {+ const getProducts = jest.fn().mockResolvedValue(page);+ await makeService({ getProducts }).svc.getProducts('s1');+ expect(getProducts).toHaveBeenCalledWith({ page: 1, limit: 20 });+ });++ it('delegates getProduct and passes an unknown id through as null (not a 404)', async () => {+ const getProduct = jest.fn().mockResolvedValue(null);+ await expect(makeService({ getProduct }).svc.getProduct('s1', 'prod-404')).resolves.toBeNull();+ expect(getProduct).toHaveBeenCalledWith('prod-404');+ });++ it('propagates an engine failure instead of reporting an empty catalog', async () => {+ const down = new NotImplementedException('catalog query unanswered');+ const getCatalog = jest.fn().mockRejectedValue(down);+ await expect(makeService({ getCatalog }).svc.getCatalog('s1')).rejects.toBe(down);+ });+ });++ describe('product-message sends', () => {+ it.each(['sendProduct', 'sendCatalog'] as const)(+ 'rejects with 404 for %s when the session is not started',+ async method => {+ const { svc } = makeService(undefined);+ const promise =+ method === 'sendProduct'+ ? svc.sendProduct('s1', '[email protected]', 'prod-1')+ : svc.sendCatalog('s1', '[email protected]');+ await expect(promise).rejects.toBeInstanceOf(NotFoundException);+ },+ );++ it('paces a product send BEFORE it reaches the engine', async () => {+ const order: string[] = [];+ const pacing = {+ assertSendAllowed: jest.fn().mockImplementation(() => {+ order.push('pace');+ return Promise.resolve();+ }),+ };+ const sendProduct = jest.fn().mockImplementation(() => {+ order.push('send');+ return Promise.resolve(sent);+ });+ const { svc } = makeService({ sendProduct }, pacing);++ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1', 'Back in stock!')).resolves.toBe(sent);+ expect(order).toEqual(['pace', 'send']);+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1', '[email protected]');+ expect(sendProduct).toHaveBeenCalledWith('[email protected]', 'prod-1', 'Back in stock!');+ });++ // No engine can send a catalog link today — the route stays live (and paced) so the day one+ // gains support the send is not unpaced, but until then the adapter's 501 must reach the+ // caller unchanged. Pin the refusal; do not "fix" it into a success.+ it('sendCatalog surfaces the engine’s deliberate 501 unchanged', async () => {+ const pacing = { assertSendAllowed: jest.fn().mockResolvedValue(undefined) };+ const unsupported = new EngineNotSupportedError('sendCatalog');+ const sendCatalog = jest.fn().mockRejectedValue(unsupported);+ const { svc } = makeService({ sendCatalog }, pacing);++ await expect(svc.sendCatalog('s1', '[email protected]', 'Browse our catalog')).rejects.toBe(unsupported);+ expect(unsupported.getStatus()).toBe(501);+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1', '[email protected]');+ expect(sendCatalog).toHaveBeenCalledWith('[email protected]', 'Browse our catalog');+ });++ it('propagates an engine failure from sendProduct', async () => {+ const down = new Error('socket closed');+ const sendProduct = jest.fn().mockRejectedValue(down);+ await expect(makeService({ sendProduct }).svc.sendProduct('s1', '[email protected]', 'prod-1')).rejects.toBe(down);+ });+ });+});diff --git a/src/modules/label/label.service.spec.ts b/src/modules/label/label.service.spec.tsindex 070b1843c..b75cbdc9b 100644--- a/src/modules/label/label.service.spec.ts+++ b/src/modules/label/label.service.spec.ts@@ -24,6 +24,67 @@ describe('LabelService', () => {await makeService({ addLabelToChat }).addLabelToChat('s1', 'chat1', 'l1');expect(addLabelToChat).toHaveBeenCalledWith('chat1', 'l1');});++ it('delegates getLabels to the engine and returns its list', async () => {+ const labels = [{ id: 'l1', name: 'VIP' }];+ const getLabels = jest.fn().mockResolvedValue(labels);+ await expect(makeService({ getLabels }).getLabels('s1')).resolves.toBe(labels);+ expect(getLabels).toHaveBeenCalledTimes(1);+ });++ it('delegates getLabelById and returns the label when it exists', async () => {+ const label = { id: 'l1', name: 'VIP' };+ const getLabelById = jest.fn().mockResolvedValue(label);+ await expect(makeService({ getLabelById }).getLabelById('s1', 'l1')).resolves.toBe(label);+ expect(getLabelById).toHaveBeenCalledWith('l1');+ });++ // Only a null lookup maps to 404 — an engine failure says nothing about whether the label+ // exists, so it must propagate unchanged rather than be reported as "not found".+ it('propagates an engine failure from getLabelById instead of mapping it to 404', async () => {+ const down = new Error('engine down');+ const getLabelById = jest.fn().mockRejectedValue(down);+ await expect(makeService({ getLabelById }).getLabelById('s1', 'l1')).rejects.toBe(down);+ });++ it('delegates getChatLabels to the engine', async () => {+ const getChatLabels = jest.fn().mockResolvedValue([{ id: 'l1' }]);+ await expect(makeService({ getChatLabels }).getChatLabels('s1', '[email protected]')).resolves.toEqual([{ id: 'l1' }]);+ expect(getChatLabels).toHaveBeenCalledWith('[email protected]');+ });++ it('delegates removeLabelFromChat to the engine', async () => {+ const removeLabelFromChat = jest.fn().mockResolvedValue(undefined);+ await makeService({ removeLabelFromChat }).removeLabelFromChat('s1', 'chat1', 'l1');+ expect(removeLabelFromChat).toHaveBeenCalledWith('chat1', 'l1');+ });++ it('throws 400 for getChatLabels and removeLabelFromChat when the session is not started', () => {+ const svc = makeService(undefined);+ expect(() => svc.getChatLabels('s1', '[email protected]')).toThrow(BadRequestException);+ expect(() => svc.removeLabelFromChat('s1', 'chat1', 'l1')).toThrow(BadRequestException);+ });++ // Every label operation is a pass-through: a rejecting engine must reach the caller as-is.+ it.each([+ ['getLabels', { getLabels: jest.fn() }, (svc: LabelService) => svc.getLabels('s1')],+ ['getChatLabels', { getChatLabels: jest.fn() }, (svc: LabelService) => svc.getChatLabels('s1', '[email protected]')],+ ['upsertLabel', { upsertLabel: jest.fn() }, (svc: LabelService) => svc.upsertLabel('s1', 'l1', { name: 'VIP' })],+ ['deleteLabel', { deleteLabel: jest.fn() }, (svc: LabelService) => svc.deleteLabel('s1', 'l1')],+ ['getChatsByLabel', { getChatsByLabel: jest.fn() }, (svc: LabelService) => svc.getChatsByLabel('s1', 'l1')],+ ['addLabelToChat', { addLabelToChat: jest.fn() }, (svc: LabelService) => svc.addLabelToChat('s1', 'chat1', 'l1')],+ [+ 'removeLabelFromChat',+ { removeLabelFromChat: jest.fn() },+ (svc: LabelService) => svc.removeLabelFromChat('s1', 'chat1', 'l1'),+ ],+ ])('propagates an engine failure from %s unchanged', async (_name, engine, call) => {+ const down = new Error('engine down');+ const method = Object.values(engine)[0];+ method.mockRejectedValue(down);++ await expect(call(makeService(engine))).rejects.toBe(down);+ });});// Create and update are one operation upstream — a single `label_edit` write keyed on the label id —diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 8feb2159f..c94e3d291 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -5,7 +5,7 @@ import type { Session } from './entities/session.entity';import type { SessionService } from './session.service';import type { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';-import { BadGatewayException } from '@nestjs/common';+import { BadGatewayException, BadRequestException, ConflictException } from '@nestjs/common';// POST /sessions declared a SessionResponseDto in its Swagger metadata but returned the raw// TypeORM entity, leaking internal columns (config, proxyUrl, proxyType) and the entity-only@@ -158,6 +158,121 @@ describe('SessionController — logout() audit + error forwarding contract', ()});});+// POST /sessions/:id/start and /stop are thin, but they carry two contracts worth pinning: the+// success audit row is written ONLY after the service resolves (a refused lifecycle change — the+// engine-not-started 400, the foreign-node 409 — must leave no audit trace), and `engineLoaded`+// in the response comes from the live engine map, not from the row's status column.+describe('SessionController — start/stop lifecycle', () => {+ const runningEntity: Session = {+ id: 'sess-uuid-1',+ name: 'test-session',+ status: SessionStatus.READY,+ phone: '628123',+ pushName: null,+ config: {},+ proxyUrl: null,+ proxyType: null,+ connectedAt: new Date('2026-01-01T01:00:00Z'),+ lastActiveAt: null,+ nodeId: null,+ claimedAt: null,+ nodeUrl: null,+ leaseExpiresAt: null,+ createdAt: new Date('2026-01-01T00:00:00Z'),+ updatedAt: new Date('2026-01-01T01:00:00Z'),+ };++ let sessionService: { start: jest.Mock; stop: jest.Mock; forceKill: jest.Mock; isActive: jest.Mock };+ let auditService: { logInfo: jest.Mock };+ let controller: SessionController;++ beforeEach(() => {+ sessionService = {+ start: jest.fn(),+ stop: jest.fn(),+ forceKill: jest.fn(),+ isActive: jest.fn().mockReturnValue(false),+ };+ auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };+ controller = new SessionControllerClass(+ sessionService as unknown as SessionService,+ auditService as unknown as AuditService,+ );+ });++ it('start returns the session with engineLoaded read from the live engine map', async () => {+ sessionService.start.mockResolvedValue({ ...runningEntity });+ sessionService.isActive.mockReturnValue(true);++ const result = await controller.start('sess-uuid-1');++ expect(result.status).toBe(SessionStatus.READY);+ expect(result.engineLoaded).toBe(true);+ expect(sessionService.isActive).toHaveBeenCalledWith('sess-uuid-1');+ });++ it('start audits SESSION_STARTED once the service has resolved', async () => {+ sessionService.start.mockResolvedValue({ ...runningEntity });++ await controller.start('sess-uuid-1');++ expect(auditService.logInfo).toHaveBeenCalledTimes(1);+ expect(auditService.logInfo).toHaveBeenCalledWith(+ AuditAction.SESSION_STARTED,+ expect.objectContaining({ sessionId: runningEntity.id, sessionName: runningEntity.name }),+ );+ });++ it('start forwards the service’s 400 verbatim and writes no audit row when the engine cannot start', async () => {+ const notStarted = new BadRequestException('Session is not started');+ sessionService.start.mockRejectedValue(notStarted);++ await expect(controller.start('sess-uuid-1')).rejects.toBe(notStarted);+ expect(auditService.logInfo).not.toHaveBeenCalled();+ });++ it('stop returns the stopped session (engineLoaded:false) and audits SESSION_STOPPED', async () => {+ sessionService.stop.mockResolvedValue({ ...runningEntity, status: SessionStatus.DISCONNECTED });++ const result = await controller.stop('sess-uuid-1');++ expect(result.status).toBe(SessionStatus.DISCONNECTED);+ expect(result.engineLoaded).toBe(false);+ expect(auditService.logInfo).toHaveBeenCalledWith(+ AuditAction.SESSION_STOPPED,+ expect.objectContaining({ sessionId: runningEntity.id, sessionName: runningEntity.name }),+ );+ });++ it('stop forwards a refusal verbatim and writes no audit row', async () => {+ const refused = new ConflictException('Another node holds this session');+ sessionService.stop.mockRejectedValue(refused);++ await expect(controller.stop('sess-uuid-1')).rejects.toBe(refused);+ expect(auditService.logInfo).not.toHaveBeenCalled();+ });++ it('forceKill audits SESSION_FORCE_KILLED after the teardown resolves', async () => {+ sessionService.forceKill.mockResolvedValue({ ...runningEntity, status: SessionStatus.DISCONNECTED });++ const result = await controller.forceKill('sess-uuid-1');++ expect(result.engineLoaded).toBe(false);+ expect(auditService.logInfo).toHaveBeenCalledWith(+ AuditAction.SESSION_FORCE_KILLED,+ expect.objectContaining({ sessionId: runningEntity.id, sessionName: runningEntity.name }),+ );+ });++ it('forceKill forwards the not-started 400 verbatim and writes no audit row', async () => {+ const notStarted = new BadRequestException('Session is not started');+ sessionService.forceKill.mockRejectedValue(notStarted);++ await expect(controller.forceKill('sess-uuid-1')).rejects.toBe(notStarted);+ expect(auditService.logInfo).not.toHaveBeenCalled();+ });+});+// Chat mute carries a nullable argument, which is the part worth pinning: `null` is the unmute// instruction, so a controller that coalesced it away (`?? undefined`, `|| 0`) would silently turn// every unmute into a mute-until-the-epoch. Both directions are asserted.diff --git a/test/message-send.e2e-spec.ts b/test/message-send.e2e-spec.tsnew file mode 100644index 000000000..0cd82306d--- /dev/null+++ b/test/message-send.e2e-spec.ts@@ -0,0 +1,199 @@+// archiver v8 is ESM-only (pulled in transitively via @Global StorageModule); stub for ts-jest CJS.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import request from 'supertest';+import { App } from 'supertest/types';+import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';+import { AuthService } from './../src/modules/auth/auth.service';+import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';+import { Session } from './../src/modules/session/entities/session.entity';+import { EngineRegistry } from './../src/engine/engine-registry.service';+import type { IWhatsAppEngine, MessageResult } from './../src/engine/interfaces/whatsapp-engine.interface';++/**+ * The send-* endpoints had no runtime exercise at all: the OpenAPI snapshot pins their route shape+ * but not that a POST actually reaches the engine and answers 201. These tests run the real HTTP+ * stack — guard, validation pipe, controller, MessageService (pacing gate, plugin gate, pending-row+ * persistence) — against a fake engine registered in the live EngineRegistry, so what is asserted+ * is the whole send path, not a controller mocked loose from its service.+ *+ * The fake engine is enough because everything else the path touches is real and local in this+ * harness: sqlite for the pending/sent rows, no enabled plugins, pacing disabled by default.+ * SIMULATE_TYPING is pinned off so the humanising pre-send pause doesn't slow the suite.+ */+describe('Message send endpoints (e2e)', () => {+ let app: INestApplication<App>;+ let sessionId: string;+ let operatorKey: string;+ const prevSimulateTyping = process.env.SIMULATE_TYPING;++ const result: MessageResult = { id: 'wamid.e2e-send', timestamp: 1_706_868_000 };+ const engine = {+ sendTextMessage: jest.fn().mockResolvedValue(result),+ sendImageMessage: jest.fn().mockResolvedValue(result),+ sendVideoMessage: jest.fn().mockResolvedValue(result),+ sendAudioMessage: jest.fn().mockResolvedValue(result),+ sendDocumentMessage: jest.fn().mockResolvedValue(result),+ sendStickerMessage: jest.fn().mockResolvedValue(result),+ sendLocationMessage: jest.fn().mockResolvedValue(result),+ sendContactMessage: jest.fn().mockResolvedValue(result),+ sendPollMessage: jest.fn().mockResolvedValue(result),+ };++ const post = (verb: string, body: unknown, session: string = sessionId) =>+ request(app.getHttpServer())+ .post(`/api/sessions/${session}/messages/${verb}`)+ .set('X-API-Key', operatorKey)+ .send(body);++ beforeAll(async () => {+ process.env.SIMULATE_TYPING = 'false';+ const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();+ app = moduleFixture.createNestApplication();+ applyGlobalValidation(app);+ await app.init();++ const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));+ sessionId = (await sessionRepo.save(sessionRepo.create({ name: `e2e-send-${Date.now()}` }))).id;++ app.get(EngineRegistry).set(sessionId, engine as unknown as IWhatsAppEngine);+ operatorKey = (await app.get(AuthService).createApiKey({ name: 'e2e-send', role: ApiKeyRole.OPERATOR })).rawKey;+ });++ afterAll(async () => {+ process.env.SIMULATE_TYPING = prevSimulateTyping;+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ beforeEach(() => jest.clearAllMocks());++ it('send-text returns 201 and hands chatId + text to the engine', async () => {+ const res = await post('send-text', { chatId: '[email protected]', text: 'hello from e2e' }).expect(201);++ expect(res.body).toEqual({ messageId: result.id, timestamp: result.timestamp });+ expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);+ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hello from e2e');+ });++ it('send-image returns 201 and hands the base64 payload to the engine', async () => {+ const base64 = Buffer.from('GIF89a').toString('base64');+ const res = await post('send-image', {+ chatId: '[email protected]',+ base64,+ mimetype: 'image/gif',+ caption: 'a gif',+ }).expect(201);++ expect(res.body).toEqual({ messageId: result.id, timestamp: result.timestamp });+ expect(engine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: base64, mimetype: 'image/gif', caption: 'a gif' }),+ );+ });++ it('send-video returns 201 and invokes the engine', async () => {+ const base64 = Buffer.from('fake-video').toString('base64');+ await post('send-video', { chatId: '[email protected]', base64, mimetype: 'video/mp4' }).expect(201);++ expect(engine.sendVideoMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: base64, mimetype: 'video/mp4' }),+ );+ });++ it('send-audio returns 201 and forwards the ptt flag as a voice note', async () => {+ const base64 = Buffer.from('fake-audio').toString('base64');+ await post('send-audio', { chatId: '[email protected]', base64, mimetype: 'audio/ogg; codecs=opus', ptt: true }).expect(+ 201,+ );++ expect(engine.sendAudioMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: base64, ptt: true }),+ );+ });++ it('send-document returns 201 and keeps the filename', async () => {+ const base64 = Buffer.from('fake-pdf').toString('base64');+ await post('send-document', {+ chatId: '[email protected]',+ base64,+ mimetype: 'application/pdf',+ filename: 'doc.pdf',+ }).expect(201);++ expect(engine.sendDocumentMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: base64, filename: 'doc.pdf' }),+ );+ });++ it('send-location returns 201 and forwards the coordinates', async () => {+ await post('send-location', {+ chatId: '[email protected]',+ latitude: -6.2088,+ longitude: 106.8456,+ description: 'Monas',+ }).expect(201);++ expect(engine.sendLocationMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ latitude: -6.2088, longitude: 106.8456, description: 'Monas' }),+ );+ });++ it('send-contact returns 201 and forwards the card', async () => {+ await post('send-contact', {+ chatId: '[email protected]',+ contactName: 'Ada',+ contactNumber: '628456',+ }).expect(201);++ expect(engine.sendContactMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ name: 'Ada', number: '628456' }),+ );+ });++ it('send-poll returns 201 and forwards the question and options', async () => {+ await post('send-poll', {+ chatId: '[email protected]',+ name: 'Lunch?',+ options: ['Nasi padang', 'Bakso'],+ }).expect(201);++ expect(engine.sendPollMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ name: 'Lunch?', options: ['Nasi padang', 'Bakso'], allowMultipleAnswers: false }),+ );+ });++ it('send-sticker returns 201 and invokes the engine', async () => {+ const base64 = Buffer.from('fake-webp').toString('base64');+ await post('send-sticker', { chatId: '[email protected]', base64, mimetype: 'image/webp' }).expect(201);++ expect(engine.sendStickerMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: base64, mimetype: 'image/webp' }),+ );+ });++ it('a send to a session with no live engine is a 400, not a 500', async () => {+ const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));+ const idle = await sessionRepo.save(sessionRepo.create({ name: `e2e-send-idle-${Date.now()}` }));++ const res = await post('send-text', { chatId: '[email protected]', text: 'hi' }, idle.id).expect(400);++ expect((res.body as { message: string }).message).toMatch(/not active/);+ expect(engine.sendTextMessage).not.toHaveBeenCalled();+ });+});