Optional - Testing Redis Storage


This video is entirely optional.

You may be asking if we should unit test the Redis storage implementation?

This is your call. The problem with unit testing this redisStorage function is that it... relies on Redis. This means Redis needs to be available when your tests are run.

Whilst that wouldn't be ideal in the long term, it can be useful to write some tests whilst playing around with redis, particularly if you're not familiar with the library.

However, I am not going to keep the unit tests that we write in this video.

I would instead look to test this functionality as part of integration testing. This would mean standing up the full API, with Redis, and then sending in real API requests.

You may disagree with this point of view, and that's absolutely fine.

In this video we will cover why writing these tests is such a pain, and how they are not true unit tests anyway. But the process can be an interesting discovery exercise, so I wanted to show it all the same.

If wanting to follow along:

mkdir __tests__/storage
touch __tests__/storage/redis.test.ts

Into which:

import { redisStorage } from "../../src/storage/redis";

describe('storage/redis', () => {

  describe('get', () => {

    it('should initially return an empty list', async () => {
      expect(
        await redisStorage.get('my_test_list_1')
      ).toEqual(
        []
      )
    });

  });

  describe('add', () => {

    const list_name = 'my_test_list_2';

    it('should allow adding an entry to the list', async () => {
      expect(
        await redisStorage.add(list_name, "chris")
      ).toEqual(
        true
      );

      expect(
        await redisStorage.get(list_name)
      ).toEqual(
        [ "chris" ]
      );

      await redisStorage.remove(list_name, "chris");
    });

  });

  describe('remove', () => {
    it('should allow removing an entry from the list', async () => {

      const list_name = 'my_test_list_3';

      await redisStorage.add(list_name, "chris");
      await redisStorage.add(list_name, "paul");

      expect(
        await redisStorage.remove(list_name, "paul")
      ).toEqual(
        true
      );

      expect(
        await redisStorage.get(list_name)
      ).toEqual(
        [ "chris" ]
      );

      await redisStorage.remove(list_name, "chris");
    });

  });

});

Remember to have Redis up and running to get these tests to work.

Episodes