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
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);

(async () => {
  for await (const m of sub) {
    const actual = TD.decode(m.data);
    expect(actual).toEqual(PAYLOAD);
  }
})().then();

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

await nc.drain();
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();