Cannot able to access dynamic test values inside “it” function of mocha, though it is accessible inside “describe” function

99封情书 提交于 2020-01-17 04:50:06

问题


I was able to access dynamic values inside describe exactly but not inside it block. (mostly I am getting last value of the array)

for( var i =0 ;i< dynamicValues.length; i++){
  (function wrap(dynamicValue){
    describe("condition", function(){
      // It is logging correct value.
      console.log(dynamicValue)
      it("should be accessible", function(){
        // It is not logging correct value, but logging last value of array.
        console.log(dynamicValue);
      }
    })
  }(dynamicValues[i]));
}

How to get same "environment" of describe inside "it" block? (This is simplified version of my logic. I am using dynamic objects in the place of array elements)

If There are array of functions,

for( var i =0 ;i< dynamicFunctions.length; i++){
  (function wrap(dynamicFunction){
    describe("condition", function(){
      // It is executing all functions.
      dynamicFunction.apply(null)
      it("should be accessible", function(){
        // It is always executing last function of the array.
        dynamicFunction.apply(null);
      }
    })
  }(dynamicFunctions[i]));
}

回答1:


Use .bind():

for(var i = 0, len = dynamicValues; i < len; i++) {
  describe('condition', function (dynamicValue) {
    it('should be accessible', function (dynamicValue) {
      console.log(dynamicValue);
    }.bind(null, dynamicValue);
  }.bind(null, dynamicValues[i]);
}


来源:https://stackoverflow.com/questions/28828300/cannot-able-to-access-dynamic-test-values-inside-it-function-of-mocha-though

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!