Skip to content

Nats

Install

1
npm install @testcontainers/nats --save-dev

Examples

These examples use the following libraries:

Choose an image from the container registry and substitute IMAGE.

Produce/consume a message

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const SUBJECT = "HELLO";
const PAYLOAD = "WORLD";
const TE = new TextEncoder();
const TD = new TextDecoder();

await using container = await new NatsContainer(IMAGE).start();
const nc = await connect(container.getConnectionOptions());

const sub = nc.subscribe(SUBJECT);

const received = (async () => {
  const messages: string[] = [];
  for await (const m of sub) {
    messages.push(TD.decode(m.data));
  }
  return messages;
})();

nc.publish(SUBJECT, TE.encode(PAYLOAD));

await nc.drain();
expect(await received).toEqual([PAYLOAD]);
await nc.close();

With credentials

1
await using container = await new NatsContainer(IMAGE).withUsername("George").withPass("1234").start();

With Jetstream

1
await using container = await new NatsContainer(IMAGE).withJetStream().start();