setDefinitionFunctionWrapper()如何在Cucumber JS中工作?

时间:2018-08-03 08:59:44

标签: javascript cucumber cucumberjs

我无法找到关于该方法如何准确工作以及如何使用的任何很好的解释。在文档中,我找到了描述:

  

setDefinitionFunctionWrapper(fn,选项)

     

设置一个用于包装步骤/挂钩定义的函数。使用时,   再次包装结果以确保其长度与   原始步骤/挂钩定义。选项是特定于步骤的   wrapperOptions,可能未定义。

我不是经验丰富的程序员,因此我不理解“包装”在这种情况下的含义。如果有人能够更有效地解释该主题,我将感到很高兴

3 个答案:

答案 0 :(得分:0)

  

包装函数是软件库或计算机程序中的子例程,其主要目的是在很少或不需要额外计算的情况下调用第二个子例程或系统调用。

程序员通常将函数与另一个函数包装在一起,以便在被包装的函数之前或之后执行一些额外的小动作。

myWrappedFunction () { doSomething }
myWrapper () { doSmallBits; myWrappedFunction(); doSmallBits; }

(1)https://en.wikipedia.org/wiki/Wrapper_function


深入CucumberJS,setDefinitionFunctionWrapper是一个将在每个步骤定义中调用的函数,并且应在调用该步骤时返回您要执行的函数。

虚拟setDefinitionFunctionWrapper的示例如下:

setDefinitionFunctionWrapper(function (fn, opts) {
  return await fn.apply(this, args);
}

答案 1 :(得分:0)

我尝试使用发布的代码片段Jorge Chip,但它不起作用。 您应该改用以下方法:

const {setDefinitionFunctionWrapper} = require('cucumber');
        
setDefinitionFunctionWrapper(function(fn){
  if(condition){//you want to do before and after step stuff
    return async function(){
      //do before step stuff
      await fn.apply(this, arguments)
      //do after step stuff
      }
  }
  else{//just want to run the step
    return fn
  }
}

在他发布的摘录中,他使用了无法使用的args,并且还在非异步功能(也无法使用)中使用了wait

答案 2 :(得分:0)

安装黄瓜库后,请参见/node_modules/cucumber/lib/support_code_library/builder.js

中的源代码

第95行:

  if (definitionFunctionWrapper) {
    definitions.forEach(function (definition) {
      var codeLength = definition.code.length;
      var wrappedFn = definitionFunctionWrapper(definition.code, definition.options.wrapperOptions);
      if (wrappedFn !== definition.code) {
        definition.code = (0, _utilArity2.default)(codeLength, wrappedFn);
      }
    });
  } else {
...

definitionFunctionWrapper基本采用代码(fn)并选择并返回新代码(fn)。

了解这段代码后,我们可以在步骤文件中实现此功能:

var { setDefinitionFunctionWrapper } = require('cucumber');

// Wrap around each step
setDefinitionFunctionWrapper(function (fn, opts) {
    return function() {
        console.log('print me in each step');
        return fn.apply(this, arguments);
    };
});
相关问题