-1

Not able to mock the redis DB for testing whether the endpoint is able to store a key and a value

**this is an end point that is used for testing **

const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient();

app.use(express.json());

app.post('/store', (req, res) => {
  const { key, value } = req.body;
  client.set(key, value, (error, result) => {
    if (error) {
      res.status(500).json({ error: 'Failed to store value' });
    } else {
      res.json({ success: true });
    }
  });
});

My test Case

const request = require('supertest');
const app = require('./app'); // Adjust the path accordingly
const redis = require('redis');
const { createClient } = require('redis-mock');

jest.mock('redis', () => ({
  createClient: jest.fn(() => createClient()),
}));

describe('POST /store', () => {
  afterEach(() => {
    // Flush Redis database after each test
    const mockClient = createClient();
    mockClient.flushall();
  });

  test('should store a value in Redis', async () => {
    const payload = {
      key: 'testKey',
      value: 'testValue',
    };

    const response = await request(app).post('/store').send(payload);

    expect(response.status).toBe(200);
    expect(response.body.success).toBe(true);

    const mockClient = createClient();
    mockClient.get(payload.key, (error, storedValue) => {
      expect(error).toBeNull();
      expect(storedValue).toBe(payload.value);
    });
  });

the test is running till line :-


jest.mock('redis', () => ({
  createClient: jest.fn(() => createClient()),
}));

and terminal is giving out an error :- Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with mock (case insensitive) are permitted. jest.mock('redis', () => ({ > 26 | createClient: jest.fn(() => createClient()),

even if i give an alias name mockclient = createClient() it is throeing out an error :- cant use mock client before before initializing async code is getting executed before initializing

  • Why can't you set up the mock like the usage of `redis-mock`? https://www.npmjs.com/package/redis-mock – Lin Du Aug 25 '23 at 02:40

0 Answers0