setDefinitionFunctionWrapper()如何在Cucumber JS中运行?

问题描述 投票:1回答:3

我无法找到有关该方法如何正常工作以及如何使用它的任何好的解释。在文档中我找到了描述:

setDefinitionFunctionWrapper(fn,options)

设置用于包装步/挂定义的函数。使用时,将再次包装结果以确保其具有与原始步骤/钩子定义相同的长度。 options是特定于步骤的wrapperOptions,可能未定义。

我不是经验丰富的程序员,我不明白在这种情况下“包装”意味着什么。如果有人能更有效地解释这个问题,我会很高兴的

javascript cucumber cucumberjs
3个回答
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);
}

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不起作用,他也在非异步函数中使用等待,这也是行不通的


0
投票

至于黄瓜2.3.1。 https://github.com/cucumber/cucumber-js/blob/2.x/src/support_code_library/builder.js

安装黄瓜库后,请参阅/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 bascially接受代码(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);
    };
});
© www.soinside.com 2019 - 2024. All rights reserved.