Supported container runtimes
Redis
登录后可跨设备保存划线和私人笔记登录
Redis
Install
1npm install @testcontainers/redis --save-devExamples
These examples use the following libraries:
-
1npm install redis
Choose an image from the container registry and substitute IMAGE.
Set/get a value
1
2
3
4
5
6
7
8
9await 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
1
2
3
4
5const 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
17const 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
16await 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
1
2
3
4
5
6
7
8
9
10await 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
1
2
3
4
5await using container = await new RedisContainer(image).start();
const queryResult = await container.executeCliCmd("info", ["clients"]);
expect(queryResult).toEqual(expect.stringContaining("connected_clients:1"));评论
登录后参与评论
正在加载评论…
KnowForge