Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(message): exercise the template, reply, forward and bulk paths over HTTP

Yudhi Armyndharis518cd77cad18
diff --git a/test/message-send.e2e-spec.ts b/test/message-send.e2e-spec.ts
index 6cd356503..e9f4d149a 100644
--- a/test/message-send.e2e-spec.ts
+++ b/test/message-send.e2e-spec.ts
@@ -25,11 +25,17 @@ import type { IWhatsAppEngine, MessageResult } from './../src/engine/interfaces/
* 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.
+ *
+ * Beyond the single-item verbs, the same harness covers send-template (resolution, rendering,
+ * the 404s), reply/forward, and the async bulk pipeline end to end: 202 envelope, per-recipient
+ * results settled through GET batch/:id, mixed success/failure, and the DTO's hard edges.
*/
describe('Message send endpoints (e2e)', () => {
let app: INestApplication<App>;
let sessionId: string;
let operatorKey: string;
+ let templateId: string;
+ let templateNameFixture: string;
const prevSimulateTyping = process.env.SIMULATE_TYPING;
const result: MessageResult = { id: 'wamid.e2e-send', timestamp: 1_706_868_000 };
@@ -43,6 +49,8 @@ describe('Message send endpoints (e2e)', () => {
sendLocationMessage: jest.fn().mockResolvedValue(result),
sendContactMessage: jest.fn().mockResolvedValue(result),
sendPollMessage: jest.fn().mockResolvedValue(result),
+ replyToMessage: jest.fn().mockResolvedValue(result),
+ forwardMessage: jest.fn().mockResolvedValue(result),
};
const post = (verb: string, body: object, session: string = sessionId) =>
@@ -51,6 +59,30 @@ describe('Message send endpoints (e2e)', () => {
.set('X-API-Key', operatorKey)
.send(body);
+ const get = (path: string, session: string = sessionId) =>
+ request(app.getHttpServer()).get(`/api/sessions/${session}/messages/${path}`).set('X-API-Key', operatorKey);
+
+ /** GET batch/:id payload, in the settled shape the assertions read. */
+ type BatchBody = {
+ batchId: string;
+ status: string;
+ progress: { total: number; sent: number; failed: number; pending: number; cancelled: number };
+ results: Array<{ chatId: string; status: string; messageId?: string; error?: { code: string; message: string } }>;
+ startedAt?: string;
+ completedAt?: string;
+ };
+
+ /** Poll the batch endpoint until the fire-and-forget processor settles the batch. */
+ const waitForBatch = async (batchId: string): Promise<BatchBody> => {
+ for (let attempt = 0; attempt < 30; attempt++) {
+ const res = await get(`batch/${batchId}`).expect(200);
+ const body = res.body as BatchBody;
+ if (body.status !== 'pending' && body.status !== 'processing') return body;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error(`batch ${batchId} did not settle within 3s`);
+ };
+
beforeAll(async () => {
process.env.SIMULATE_TYPING = 'false';
const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();
@@ -63,6 +95,21 @@ describe('Message send endpoints (e2e)', () => {
app.get(EngineRegistry).set(sessionId, engine as unknown as IWhatsAppEngine);
operatorKey = (await app.get(AuthService).createApiKey({ name: 'e2e-send', role: ApiKeyRole.OPERATOR })).rawKey;
+
+ // A real template row via the real route, so send-template exercises resolution and rendering
+ // against persisted data rather than a seeded fixture.
+ templateNameFixture = `e2e-greet-${Date.now()}`;
+ const template = await request(app.getHttpServer())
+ .post(`/api/sessions/${sessionId}/templates`)
+ .set('X-API-Key', operatorKey)
+ .send({
+ name: templateNameFixture,
+ header: 'Hi',
+ body: 'Hello {{customer}}, order {{orderId}} is ready.',
+ footer: 'Thanks',
+ })
+ .expect(201);
+ templateId = (template.body as { id: string }).id;
});
afterAll(async () => {
@@ -187,6 +234,145 @@ describe('Message send endpoints (e2e)', () => {
);
});
+ it('send-template renders the resolved template and sends it as text', async () => {
+ const res = await post('send-template', {
+ chatId: '[email protected]',
+ templateName: templateNameFixture,
+ vars: { customer: 'Ada', orderId: '42' },
+ }).expect(201);
+
+ expect(res.body).toEqual({ messageId: result.id, timestamp: result.timestamp });
+ expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);
+ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi\n\nHello Ada, order 42 is ready.\n\nThanks');
+ });
+
+ it('send-template also resolves by id', async () => {
+ await post('send-template', {
+ chatId: '[email protected]',
+ templateId,
+ vars: { customer: 'Grace', orderId: '7' },
+ }).expect(201);
+
+ expect(engine.sendTextMessage).toHaveBeenCalledWith(
+ 'Hi\n\nHello Grace, order 7 is ready.\n\nThanks',
+ );
+ });
+
+ it('send-template with an unknown name is a 404 and never reaches the engine', async () => {
+ const res = await post('send-template', { chatId: '[email protected]', templateName: 'missing' }).expect(404);
+
+ expect((res.body as { message: string }).message).toMatch(/not found/);
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ });
+
+ it('send-template without either identifier is a 404 naming the requirement', async () => {
+ const res = await post('send-template', { chatId: '[email protected]' }).expect(404);
+
+ expect((res.body as { message: string }).message).toBe('Either templateId or templateName must be provided');
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ });
+
+ it('reply returns 201 and quotes the original message', async () => {
+ const res = await post('reply', {
+ chatId: '[email protected]',
+ quotedMessageId: 'wamid.quoted.1',
+ text: 'replying',
+ }).expect(201);
+
+ expect(res.body).toEqual({ messageId: result.id, timestamp: result.timestamp });
+ expect(engine.replyToMessage).toHaveBeenCalledTimes(1);
+ expect(engine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wamid.quoted.1', 'replying');
+ });
+
+ it('forward returns 201 and forwards via the engine', async () => {
+ const res = await post('forward', {
+ fromChatId: '[email protected]',
+ toChatId: '[email protected]',
+ messageId: 'wamid.src.1',
+ }).expect(201);
+
+ expect(res.body).toEqual({ messageId: result.id, timestamp: result.timestamp });
+ expect(engine.forwardMessage).toHaveBeenCalledTimes(1);
+ expect(engine.forwardMessage).toHaveBeenCalledWith('[email protected]', '[email protected]', 'wamid.src.1');
+ });
+
+ it('send-bulk answers 202 with the batch envelope, then settles through the batch endpoint', async () => {
+ const res = await post('send-bulk', {
+ messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'bulk one' } }],
+ }).expect(202);
+
+ const body = res.body as {
+ batchId: string;
+ status: string;
+ totalMessages: number;
+ statusUrl: string;
+ estimatedCompletionTime: string;
+ };
+ const batchId: string = body.batchId;
+ expect(batchId).toMatch(/^batch_/);
+ expect(body.status).toBe('pending');
+ expect(body.totalMessages).toBe(1);
+ expect(body.statusUrl).toBe(`/api/sessions/${sessionId}/messages/batch/${batchId}`);
+ expect(body.estimatedCompletionTime).toEqual(expect.any(String));
+
+ const settled = await waitForBatch(batchId);
+ expect(settled.status).toBe('completed');
+ expect(settled.progress).toEqual({ total: 1, sent: 1, failed: 0, pending: 0, cancelled: 0 });
+ expect(settled.results).toEqual([
+ expect.objectContaining({ chatId: '[email protected]', status: 'sent', messageId: result.id }),
+ ]);
+ expect(settled.startedAt).toEqual(expect.any(String));
+ expect(settled.completedAt).toEqual(expect.any(String));
+
+ expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);
+ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'bulk one');
+ });
+
+ it('send-bulk reports per-recipient outcomes with variables applied', async () => {
+ engine.sendTextMessage.mockResolvedValueOnce(result).mockRejectedValueOnce(new Error('engine refused'));
+
+ const res = await post('send-bulk', {
+ messages: [
+ { chatId: '[email protected]', type: 'text', content: { text: 'hey {{name}}' }, variables: { name: 'Bo' } },
+ { chatId: '[email protected]', type: 'text', content: { text: 'second' } },
+ ],
+ options: { delayBetweenMessages: 1000, randomizeDelay: false },
+ }).expect(202);
+ expect((res.body as { totalMessages: number }).totalMessages).toBe(2);
+
+ const settled = await waitForBatch((res.body as { batchId: string }).batchId);
+ expect(settled.status).toBe('completed');
+ expect(settled.progress).toEqual({ total: 2, sent: 1, failed: 1, pending: 0, cancelled: 0 });
+ expect(engine.sendTextMessage).toHaveBeenNthCalledWith(1, '[email protected]', 'hey Bo');
+ expect(settled.results[1]).toEqual(
+ expect.objectContaining({
+ chatId: '[email protected]',
+ status: 'failed',
+ error: { code: 'SEND_FAILED', message: 'engine refused' },
+ }),
+ );
+ });
+
+ it('send-bulk rejects a delay under the 1s floor', async () => {
+ await post('send-bulk', {
+ messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'x' } }],
+ options: { delayBetweenMessages: 500 },
+ }).expect(400);
+ });
+
+ it('send-bulk rejects a message type the batch does not carry', async () => {
+ await post('send-bulk', {
+ messages: [{ chatId: '[email protected]', type: 'sticker', content: {} }],
+ }).expect(400);
+ });
+
+ it('batch status for an unknown id is a 404 naming it', async () => {
+ const res = await get('batch/does-not-exist').expect(404);
+
+ expect((res.body as { message: string }).message).toBe("Batch 'does-not-exist' not found");
+ });
+
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()}` }));