Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

2.2 KB
Raw Blame
import { NotImplementedException } from '@nestjs/common';
import { LabelController } from './label.controller';
import type { LabelService } from './label.service';
import { ChatScopeService } from '../auth/chat-scope.service';
import type { ApiKey } from '../auth/entities/api-key.entity';

describe('LabelController - GET :labelId/chats for a chat-restricted key', () => {
  const getChatsByLabel = jest.fn();
  const controller = new LabelController({ getChatsByLabel } as unknown as LabelService, new ChatScopeService());
  const chats = [{ id: '[email protected]' }, { id: '[email protected]' }, { id: '[email protected]' }];

  beforeEach(() => getChatsByLabel.mockReset());

  it('returns only the chats inside the key allowlist', async () => {
    getChatsByLabel.mockResolvedValue(chats);
    const out = await controller.getChatsByLabel('s1', 'l1', { allowedChats: ['[email protected]'] } as ApiKey);
    expect(getChatsByLabel).toHaveBeenCalledWith('s1', 'l1');
    expect(out).toEqual([{ id: '[email protected]' }]);
  });

  it('passes every chat through for an unrestricted key', async () => {
    getChatsByLabel.mockResolvedValue(chats);
    await expect(controller.getChatsByLabel('s1', 'l1', { allowedChats: null } as ApiKey)).resolves.toEqual(chats);
  });

  it('lets an engine refusal through unchanged', async () => {
    getChatsByLabel.mockRejectedValue(new NotImplementedException('no label query'));
    await expect(controller.getChatsByLabel('s1', 'l1', { allowedChats: ['[email protected]'] } as ApiKey)).rejects.toThrow(
      NotImplementedException,
    );
  });
});

// Every label route reaches the engine through EngineRegistry.require(), which answers 400 for a
// session with no live engine; clients generated from the OpenAPI contract need it declared.
describe('LabelController OpenAPI error responses', () => {
  it.each([
    'findAll',
    'findOne',
    'getChatsByLabel',
    'upsertLabel',
    'deleteLabel',
    'getChatLabels',
    'addLabelToChat',
    'removeLabelFromChat',
  ])('%s declares 400', method => {
    const responses = Reflect.getMetadata(
      'swagger/apiResponse',
      Object.getOwnPropertyDescriptor(LabelController.prototype, method)!.value as object,
    ) as Record<string, unknown>;
    expect(Object.keys(responses)).toContain('400');
  });
});