javascript - 带有 sinon 返回函数的 stub 函数?

标签 javascript node.js redis sinon stub

我想进行单元测试并覆盖我的代码,这是我的代码,如何用 sinon 覆盖 createClient?

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

最佳答案

测试分配给 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
  ...
})

关于javascript - 带有 sinon 返回函数的 stub 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54971455/

相关文章:

caching - 如何从 redis-cli repl 中删除 Redis 匹配模式中的所有键?

javascript - Jquery:单击按钮时打开一个新的 HTML 窗口

javascript - 警报 ('hello' );在 pageLoad() 函数中工作?

javascript - 将对象插入 javascript 深拷贝还是浅拷贝中的数组?

javascript - anchor 标记到页面中间

php - 将 PHP 加密/解密转换为 Node.js

redis - 如何在flink map()中使用Jedis

javascript - 有没有一种有效的方法来区分由 `npm list` 填充的两个依赖关系树?

node.js - socket.io net::ERR_CONNECTION_CLOSED

redis - 用于Redis得分排序集的Hazelcast和Apache Ignite模拟