I want to make unit testing and cover my code, this is my code, how can cover the createClient with sinon ?
const client = redis.createClient({
retry_strategy: function(options) {
if (options.error) {
if (options.error.code === 'ECONNREFUSED') {
return new Error('The server refused the connection');
}
if (options.error.code === 'ECONNRESET') {
return new Error('The server reset the connection');
}
if (options.error.code === 'ETIMEDOUT') {
return new Error('The server timeouted the connection');
}
}
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error('Retry time exhausted');
}
if (options.attempt > 10) {
return undefined;
}
return Math.min(options.attempt * 100, 3000);
}
The easiest way to test the function assigned to retry_strategy
would be to move it outside the redis.createClient
call and export it:
export const retryStrategy = function (options) {
if (options.error) {
if (options.error.code === 'ECONNREFUSED') {
return new Error('The server refused the connection');
}
if (options.error.code === 'ECONNRESET') {
return new Error('The server reset the connection');
}
if (options.error.code === 'ETIMEDOUT') {
return new Error('The server timeouted the connection');
}
}
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error('Retry time exhausted');
}
if (options.attempt > 10) {
return undefined;
}
return Math.min(options.attempt * 100, 3000);
}
const client = redis.createClient({
retry_strategy: retryStrategy
...
Then you can import it and test it directly:
import { retryStrategy } from './your-module';
test('retryStrategy', () => {
expect(retryStrategy({ attempt: 5 })).toBe(500); // SUCCESS
...
})