0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【typescript】ioredis-mockを用いてjestでのredisのテストを行う

Last updated at Posted at 2022-08-26

ioredis-mockって何?

ioredisの全ての操作をメモリ内で実行するエミュレーター。実際にサーバーにアクセスすることなしにioredisをモック化することができる。

今回はこれをFakeとして用いてRedisのテストを行う。

導入

npm i ioredis-mock

@types/ioredis-mockという型定義ファイルもあるが、こちらは思ったように使用することができなかったためrequire("ioredis-mock")としてimportする。

使ってみよう

redisインスタンスは以下のように作ることができる。

const Redis = require("ioredis-mock");

const redis = new Redis();

ioredisと全く同じように使ってみよう。

redis.test.ts
const Redis = require("ioredis-mock");

const redis = new Redis();

it("should get value", async () => {
    const id = "hoge";
    const value = "fuga";
    await redis.set(id, value);
    const gotValue = await redis.get(id); 
    expect(gotValue).toEqual(value);
});

設定した値を再び取り出すだけ。特にサーバーなど何も設定せずこれだけで動かせる。

expireを試してみよう

jest上で動かすため、redis上で経過する時間をテスト上で好きに制御することができる。

it("should expire", async () => {
    jest.useFakeTimers();
    const id = "hoge";
    const value = "fuga";
    await redis.set(id, value, "EX", 60);
    jest.advanceTimersByTime(60_000);
    const gotValue = await redis.get(id); 
    expect(gotValue).toBeNull();
});

60秒後に有効期限切れとなるキーを設定し、60秒経過させて取り出す。値がnullとなることを確認した。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?