在javascript中使用反射来获取失败时测试函数的名称

时间:2015-04-21 07:53:12

标签: javascript node.js reflection mocha async.js

我们如何确定被调用的变量函数的名称?

我有一个函数,可以作为测试实用程序函数来设置我的测试用例。根据测试传递给测试实用程序功能的参数,某些子功能可能会也可能不会执行。有时这些子功能失败,我需要知道哪一个失败,但我不知道如何做到这一点。在其他语言中,反思是我在这里使用的。这是一个选择吗?

这是我们正在做的事情的抽象例子:

exports.test_util_func = function(params, callback){
 //initialize the functions
 var a = function(callback){
  ...
  //response might be "{status:400, body: {error: {...} } }"
  callback(error, response);
 }
 var b = function(callback){
  ...
  callback(error, response);
 }
 //determine what functions to run
 var functions_to_run = [];
 if(params.a) functions_to_run.push(a);
 if(params.b) functions_to_run.push(a);
 async.series(functions, function(error, responses){
  if(error) throw new Error(error);
  for(var i in responses){(function(response){
    //verify that we received a 200 success status from the server
    //if we didn't, capture the error
    if(response.status!==200){
      console.log(response.body);
      console.log(i);
      //HELP NEEDED HERE - how do we capture better than the function iteration so we know what actually failed? Ideally, we would have: "reflective call()
      throw new Error(i+": "+JSON.stringify(response.body));
    }
  })(responses[i]);}
 })
}

编辑:我们可以使用以下帖子中的内容,但我想通过使用__prototype信息必须有一些更简单的方法:Get variable name. javascript "reflection"

1 个答案:

答案 0 :(得分:0)

我找到了一种解决方法,可以让我继续使用这种模式,但并不完全健壮。在创建函数之后,我们创建use将名称存储在函数的原型中。

理想情况仍然是能够引用变量名称本身。

最终代码示例:

exports.test_util_func = function(params, callback){
 //initialize the functions
 var a = function(callback){
  ...
  //response might be "{status:400, body: {error: {...} } }"
  callback(error, response);
 }
 a.prototype.name = "a";
 var b = function(callback){
  ...
  callback(error, response);
 }
 a.prototype.name = "b";
 //determine what functions to run
 var functions_to_run = [];
 if(params.a) functions_to_run.push(a);
 if(params.b) functions_to_run.push(a);
 async.series(functions, function(error, responses){
  if(error) throw new Error(error);
  for(var i in responses){(function(response){
    //verify that we received a 200 success status from the server
    //if we didn't, capture the error
    if(response.status!==200){
      console.log(functions.map(function(func){return func.prototype.name})[i]);
      console.log(response.body);
    }
  })(responses[i]);}
 })
}