Функция заглушки с функцией возврата с помощью sinon? - PullRequest
0 голосов
/ 03 марта 2019

Я хочу провести модульное тестирование и покрыть свой код, это мой код, как можно покрыть createClient с помощью 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);
  }

Ответы [ 2 ]

0 голосов
/ 04 марта 2019

Другой подход, который вы можете использовать, - это использовать proxyquire для насмешки redis.createClient, чтобы вернуть opt, чтобы мы могли получить доступ к retry_strategy.В тесте мы вызываем retry_strategy и передаем его options

// test.js
const proxyquire = require('proxyquire');
const src = proxyquire('./your-source-file', { 'redis': { createClient(opt) { 
  return opt 
}}});
const chai = require('chai');
const expect = chai.expect;

describe('testing redis ', function() {
  it('refuses connection', function() {
    const options = {
      error: {
        code: 'ECONNREFUSED'
      }
    }

    expect(src.retry_strategy(options).message).to.equal('The server refused the connection');            
  });
});

Вот исходный файл, который я использовал для тестирования

// source.js
const redis = require('redis');

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);
  }
});

module.exports = client;
0 голосов
/ 04 марта 2019

Самый простой способ проверить функцию, назначенную для retry_strategy, это переместить ее за пределы вызова redis.createClient и экспортировать ее:

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
  ...

Затем вы можете импортировать ее и проверить напрямую:

import { retryStrategy } from './your-module';

test('retryStrategy', () => {
  expect(retryStrategy({ attempt: 5 })).toBe(500);  // SUCCESS
  ...
})
...