Redis
Install
|  | npm install @testcontainers/redis --save-dev
 | 
Examples
These examples use the following libraries:
Choose an image from the container registry and substitute IMAGE.
Set/get a value
|  | await using container = await new RedisContainer(IMAGE).start();
const client = createClient({ url: container.getConnectionUrl() });
await client.connect();
await client.set("key", "val");
expect(await client.get("key")).toBe("val");
client.destroy();
 | 
With password
|  | const password = "testPassword";
await using container = await new RedisContainer(IMAGE).withPassword(password).start();
expect(container.getConnectionUrl()).toEqual(`redis://:${password}@${container.getHost()}:${container.getPort()}`);
 | 
With persistent data
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17 | const sourcePath = fs.mkdtempSync("redis-");
await using container = await new RedisContainer(IMAGE).withPassword("test").withPersistence(sourcePath).start();
let client = createClient({ url: container.getConnectionUrl() });
await client.connect();
await client.set("key", "val");
client.destroy();
await container.restart();
client = createClient({ url: container.getConnectionUrl() });
await client.connect();
expect(await client.get("key")).toBe("val");
client.destroy();
fs.rmSync(sourcePath, { force: true, recursive: true });
 | 
With predefined data
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16 | await using container = await new RedisContainer(IMAGE)
  .withPassword("test")
  .withInitialData(path.join(__dirname, "initData.redis"))
  .start();
const client = createClient({ url: container.getConnectionUrl() });
await client.connect();
const user = {
  first_name: "David",
  last_name: "Bloom",
  dob: "03-MAR-1981",
};
expect(await client.get("user:002")).toBe(JSON.stringify(user));
client.destroy();
 | 
Redis stack
|  | await using container = await new RedisContainer(REDISSTACK_IMAGE).withPassword("testPassword").start();
const client = createClient({ url: container.getConnectionUrl() });
await client.connect();
await client.json.set("key", "$", { name: "test" });
const result = await client.json.get("key");
expect(result).toEqual({ name: "test" });
client.destroy();
 | 
Execute a command inside the container
|  | await using container = await new RedisContainer(IMAGE).start();
const queryResult = await container.executeCliCmd("info", ["clients"]);
expect(queryResult).toEqual(expect.stringContaining("connected_clients:1"));
 |