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']
])))