|
| 1 | +import { randomUUID } from 'node:crypto' |
| 2 | +import { KafkaJS } from '@confluentinc/kafka-javascript' |
| 3 | +import { waitAndRetry } from '@lokalise/universal-ts-utils/node' |
| 4 | +import {} from '@platformatic/kafka' |
| 5 | +import { type TestContext, registerDependencies } from '../test/testContext.ts' |
| 6 | + |
| 7 | +describe('Test confluentic-kafka', () => { |
| 8 | + let testContext: TestContext |
| 9 | + |
| 10 | + beforeAll(async () => { |
| 11 | + testContext = await registerDependencies() |
| 12 | + }) |
| 13 | + |
| 14 | + afterAll(async () => { |
| 15 | + await testContext.dispose() |
| 16 | + }) |
| 17 | + |
| 18 | + it('should send and receive a message', async () => { |
| 19 | + // Given |
| 20 | + const clientId = randomUUID() |
| 21 | + const groupId = randomUUID() |
| 22 | + // Use a fresh, unique topic per run to avoid stale state |
| 23 | + const topic = `test-topic-${Date.now()}` |
| 24 | + const messageValue = 'My test message' |
| 25 | + |
| 26 | + const kafka = new KafkaJS.Kafka({ |
| 27 | + 'client.id': clientId, |
| 28 | + 'bootstrap.servers': testContext.cradle.kafkaConfig.brokers.join(','), |
| 29 | + }) |
| 30 | + |
| 31 | + // Topics can be created from producers, but as we will first connect a consumer, we need to create the topic first |
| 32 | + const admin = kafka.admin() |
| 33 | + await admin.connect() |
| 34 | + await admin.createTopics({ |
| 35 | + topics: [{ topic }], |
| 36 | + }) |
| 37 | + |
| 38 | + const messages: string[] = [] |
| 39 | + |
| 40 | + const consumer = kafka.consumer({ 'group.id': groupId }) |
| 41 | + await consumer.connect() |
| 42 | + await consumer.subscribe({ topic }) |
| 43 | + |
| 44 | + await consumer.run({ |
| 45 | + eachMessage: ({ message }) => { |
| 46 | + const messageString = message.value?.toString() |
| 47 | + if (messageString) messages.push(messageString) |
| 48 | + return Promise.resolve() |
| 49 | + }, |
| 50 | + }) |
| 51 | + // Wait for the consumer to be assigned partitions |
| 52 | + await waitAndRetry(() => consumer.assignment().length > 0, 100, 10) |
| 53 | + |
| 54 | + // When |
| 55 | + const producer = kafka.producer() |
| 56 | + await producer.connect() |
| 57 | + await producer.send({ |
| 58 | + topic, |
| 59 | + messages: [{ value: messageValue }], |
| 60 | + }) |
| 61 | + |
| 62 | + // Then |
| 63 | + await waitAndRetry(() => messages.length > 0) |
| 64 | + |
| 65 | + // Cleaning up before checks to avoid stale state |
| 66 | + await consumer.disconnect() |
| 67 | + await producer.disconnect() |
| 68 | + await admin.disconnect() |
| 69 | + |
| 70 | + expect(messages).toHaveLength(1) |
| 71 | + expect(messages[0]).toEqual(messageValue) |
| 72 | + }) |
| 73 | +}) |
0 commit comments