Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
In Jest, mock the constructor of a class instantiated in the tested function

I want to test getSessionStorage(). Inside getSessionStorage() I'm calling new RedisStore(process.env.REDIS_URL). This throws an error because process.env.REDIS_URL is not accessible outside a vpn.

How can I mock RedisStore.constructor to avoid calling this.client.connect(); and thus avoid the error?

RedisStore.js

import { createClient } from "redis";

class RedisStore {
  /**
   * @param {string} url
   */
  constructor(url) {
    this.client = createClient({ url });
    this.client.on("error", (err) => console.log("Redis Client Error", err));
    this.client.connect();
  }
  
  async storeCallback(session) {}
  async loadCallback(id) {}
  async deleteCallback(id) {}

}
export default RedisStore;

getSessionStorage.js

import RedisStore from "./RedisStore";

const getSessionStorage = ()=> {
  return new RedisStore(process.env.REDIS_URL);
}

export default getSessionStorage;

getSessionStorage.test.js

import getSessionStorage from "./getSessionStorage.js";

describe("getSessionStorage", () => {
  it("should pass", () => {
    expect(getSessionStorage()).toMatchObject({
      storeCallback: expect.any(Function),
      loadCallback: expect.any(Function),
      deleteCallback: expect.any(Function)
    });
  });
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can mock redis:

jest.mock('redis', () => ({
    createClient : jest.fn().mockReturnValue({ 
        on: jest.fn(),
        connect: jest.fn() 
    }),
}));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!