Why my jest tests are not using my mock Class? How to fix it?

19 views Asked by At

Why my tests are not using the mock functions? The tests are failing because they are calling the actual initClient function inside the LaunchDarklyClient

launchDarkly.ts

export class LaunchDarklyClient {
  client: LDClient;

  constructor() {}

  async initClient(ldKeySecretName: string) {
    console.log('ldKeySecretName is: ', ldKeySecretName);
    const sdkKeyResponse = await getSecret({
      SecretId: ldKeySecretName,
    });

    const sdkKey = sdkKeyResponse.SecretString;
    try {
      console.log('Initializing LaunchDarkly');
      const client = ld.init(sdkKey);

      this.client = client;
    } catch (err) {
      console.error('Error initializing LaunchDarkly: ', err);
    }
  }

  async getFeatureFlag(key: string): Promise<any> {
    console.log('Fetching feature flag: ', key);
    try {
      const ldContext = {
        key: 'anonymous',
      };
      const result = await this.client.variation(key, ldContext, false);

      return result;
    } catch (err) {
      console.error('Couldnt get feature flag from LaunchDarkly: ', err);
      return null;
    }
  }
}

export const getFeatureFlags = async (
  ldKey: string,
  flagNames: string[],
): Promise<iFlags> => {
  const ldClient = new LaunchDarklyClient();
  const flags: iFlags = {};

  try {
    await ldClient.initClient(ldKey);
    await ldClient.client.waitForInitialization();

    for (const flagName of flagNames) {
      const flagValue = await ldClient.getFeatureFlag(flagName);
      flags[flagName] = flagValue;
    }
  } catch (err) {
    console.error('LaunchDarkly client did not initialize: ', err);
    flagNames.forEach((flagName) => (flags[flagName] = null));
  }

  console.log('returning feature flags: ', flags);
  return flags;
};

launchDarkly.spec.ts

import { getFeatureFlags, LaunchDarklyClient } from './launchDarkly';

jest.mock('./launchDarkly', () => {
    return {
        ...jest.requireActual('./launchDarkly'),
        LaunchDarklyClient:jest.fn().mockImplementation(() => {
            return {
              initClient: jest.fn(),
              client: {
                waitForInitialization: jest.fn(),
              },
              getFeatureFlag: jest.fn(),
            };
        })
    }
});

describe('getFeatureFlags', () => {
  const ldKey = 'test-ld-key';
  const flagNames = ['flag1', 'flag2'];
  let ldClient;

  beforeEach(() => {
    ldClient = new LaunchDarklyClient();
  });

  it('should return flags when LaunchDarkly client initializes successfully', async () => {
    ldClient.initClient.mockResolvedValue(undefined);
    ldClient.client.waitForInitialization.mockResolvedValue(undefined);
    ldClient.getFeatureFlag.mockImplementation(flagName => Promise.resolve(flagName + '-value'));

    const flags = await getFeatureFlags(ldKey, flagNames);

    expect(ldClient.initClient).toHaveBeenCalledWith(ldKey);
    expect(ldClient.client.waitForInitialization).toHaveBeenCalled();
    flagNames.forEach(flagName => {
      expect(ldClient.getFeatureFlag).toHaveBeenCalledWith(flagName);
      expect(flags[flagName]).toEqual(flagName + '-value');
    });
  });

  it('should return null for all flags when LaunchDarkly client initialization fails', async () => {
    ldClient.initClient.mockRejectedValue(new Error('Initialization failed'));

    const flags = await getFeatureFlags(ldKey, flagNames);

    expect(ldClient.initClient).toHaveBeenCalledWith(ldKey);
    expect(ldClient.client.waitForInitialization).not.toHaveBeenCalled();
    flagNames.forEach(flagName => {
      expect(flags[flagName]).toBeNull();
    });
  });
});
0

There are 0 answers