Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Last active August 18, 2021 17:39
Show Gist options
  • Save farhad-taran/2c655ca0d46a4ab33272f3dcc3171c73 to your computer and use it in GitHub Desktop.
Save farhad-taran/2c655ca0d46a4ab33272f3dcc3171c73 to your computer and use it in GitHub Desktop.
reusable key value pair mock for services such as config providers

sometimes we want to stub a service that returns a value for a key, for example a config provider. the following reusable construct uses jest which can reduce the number of duplicated boiler plate code.

export default (mockedMethodName: string, keyValueMap: Map<string, string>) => {
  const mock = {};
  mock[mockedMethodName] = (key: string) => {
    const value = keyValueMap.get(key);
    if (!value) {
      throw new Error(`${key} not present in ${mockedMethodName} in keyValueMock`);
    }
    return value;
  };
  return mock;
};

and here is and example of how its used in a nestJs test:

....
.overrideProvider(SecretsService)
        .useValue(keyValueMock('getSecret',new Map<string,string>([
          ['qwickcilver-api-auth-token-prod','qwickcilver_prod_bearer'], 
          ['qwickcilver-api-auth-token-staging','qwickcilver_staging_bearer']
        ])))
        .overrideProvider(ConfigService)
        .useValue(keyValueMock('get',new Map<string,string>([
          ['qwikcilver.encryptionKey', 'vOVH6sdmpNWjRRIqCc7rdxs01lwHzfr3'],
          ['qwikcilver.auth.staging.apiEndpoint', 'qwickcilver_staging_base_url'],
          ['qwikcilver.auth.production.apiEndpoint', 'qwickcilver_prod_base_url'],
          ['qwikcilver.auth.production.tokenKey','qwickcilver-api-auth-token-prod'],
          ['qwikcilver.auth.staging.tokenKey','qwickcilver-api-auth-token-staging'],
          ['auth.user', 'test'],
          ['auth.pass', 'pass']
        ])))

you can even return a promis if the service that you are mocking returns promises:

....
.overrideProvider(SecretsService)
        .useValue(keyValueMock('getSecret',new Map<string,string>([
          ['qwickcilver-api-auth-token-prod', Promise.resolve('qwickcilver_prod_bearer']), 
          ['qwickcilver-api-auth-token-staging','qwickcilver_staging_bearer']
        ])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment