javascript - 测试/检查变量的限制是什么?

标签 javascript node.js unit-testing methodology

我有一个可以扩展的 javascript 类。

当我编写单元测试时,我看到了可以捕获的错误。
因此,我在第一个函数 extractParameterMethodForRequest 中添加了用于检查类属性的测试。
但现在当我阅读我的函数时,有很多噪音。

你觉得这样检查有用吗?也许我必须合并一些异常才能提供一般错误?

function MyClass(){
  this.validHttpMethods = ['GET', 'POST'];
  this.defaultValues = {
    method: 'GET'
  };
}

/**
 * Extract "method" from parameters
 * @param {MyClass~RawParameters} parameters
 * @return {string} A validate Methods belong to validHttpMethods
 */
MyClass.prototype.extractParameterMethodForRequest = function (parameters) {
  var idx;
  var method;

  if(parameters === undefined || parameters === null) {
    throw Error('REQ-001 parameters undefined');
  }

  if(parameters.method) {
    if(typeof parameters.method !== 'string') {
      throw Error('REQ-002 method not a string');
    }

    method = parameters.method;
  }
  else {
    if(this.defaultValues === undefined) {
      throw Error('REQ-003 this.defaultValues undefined');
    }

    if(this.defaultValues.method === undefined) {
      throw Error('REQ-004 default method undefined');
    }

    if(typeof this.defaultValues.method !== 'string') {
      throw Error('REQ-005 default method not a string');
    }

    method = this.defaultValues.method;
  }

  method = method.trim().toUpperCase();

  if(method.length < 1) {
    throw this.RError('REQ-006 method empty');
  }

  if(this.validHttpMethods === undefined) {
    throw this.RError('REQ-007 this.validHttpMethods undefined');
  }

  if(!(this.validHttpMethods instanceof Array)) {
    throw this.RError('REQ-008 this.validHttpMethods not an array');
  }

  idx = this.validHttpMethods.indexOf(method);
  if(idx === -1) {
    throw this.RError('REQ-009 method %s invalid', method);
  }

  return this.validHttpMethods[idx];
};

最佳答案

测试/检查变量没有限制。但如果您觉得它使您的函数可读性较差,那么您可以随时将参数检查代码放在其他地方。

此外,您还可以用更短的方式编写它。例如这个:

if(parameters === undefined || parameters === null) {
  throw Error('REQ-001 parameters undefined');
}
if(parameters.method) {
  if(typeof parameters.method !== 'string') {
    throw Error('REQ-002 method not a string');
  }
}

可以写成:

if(!parameters || parameters.method && typeof parameters.method !== 'string') {
  throw Error('bad arguments');
}

甚至:

assert(!parameters || parameters.method && typeof parameters.method !== 'string');

现在的写法非常冗长。

关于javascript - 测试/检查变量的限制是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40722913/

相关文章:

javascript - 对象拆包赋值操作?

javascript - Discord API 对于使用机器人 token 的所有查询返回 401

javascript - html5 拖放是否在 Windows 的 Safari 浏览器上损坏?

javascript - 对混合 Angular/React 应用程序进行单元测试

javascript - 导出到 Excel 在 Internet Explorer 11 中不起作用

node.js - 如何使用 AWS 开发工具包(在 Node.js 中)中的 putObject() 将文件从 HTTP 响应正文上传到 S3?

javascript - 如何通过 Electron 获取唯一的 PC ID?

c# - TransactionScope 未在 MSTest 测试中回滚

unit-testing - 单元测试 SLF4J 日志消息的最佳方法是什么?

javascript - 使用 puppeteer 选择表格的第二行