简体   繁体   English

Cucumber-js 中的装饰步骤实现

[英]Decorate step implementation in Cucumber-js

Introduction介绍

Im using https://github.com/cucumber/cucumber-js in typescript.我在打字稿中使用https://github.com/cucumber/cucumber-js Sample of code implementation looks like average cucumber implementation:代码实现示例看起来像普通的黄瓜实现:

import {
    Given,
    Then,
    When
} from 'cucumber'

Given(`Page is up and running`, function(this: World) {
    someFunction()
})

Goal目标

What I would like to achieve is to be able to somehow decorate Given , so that:我想要实现的是能够以某种方式装饰Given ,以便:

  • some action can be invoked before code inside Given .可以在Given中的代码之前调用某些操作。 Lets say, for simple example, I would like to print first Given argument (so Page is up and running ).可以说,举个简单的例子,我想打印第一个Given参数(所以Page is up and running )。
  • there would be no need to modify existing step implementation.无需修改现有的步骤实现。

Each step got two alias function definitions in index.d.ts , eg:每个步骤在index.d.ts中都有两个别名函数定义,例如:

export function Given(pattern: RegExp | string, code: StepDefinitionCode): void;
export function Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void;

In the original version of CucumberJS, there were more hooks available including beforeStep .在 CucumberJS 的原始版本中,有更多可用的钩子,包括beforeStep However, there is a way to achieve this functionality in versions of the framework such as 6.0.5 using setDefinitionFunctionWrapper .但是,有一种方法可以使用setDefinitionFunctionWrapper在框架版本(例如 6.0.5)中实现此功能。 Example:例子:

setDefinitionFunctionWrapper(fn => async function step(...args) {
    //
    // do something before the step definition runs.
    //
    const result = await fn.apply(this, args);
    //
    // do something after the step definition runs.
    //
    return result;
});

Online Example: https://testjam.io/?p=O2wodDVOveAMdA9HKMKy在线示例: https ://testjam.io/?p=O2wodDVOveAMdA9HKMKy

Known limitations and caveats :已知的限制和注意事项

  • This function will wrap every step definition AND hook.这个函数将包装每一步定义和钩子。
  • This particular implementation assumes that the step definition or hook is not using a callback.此特定实现假定步骤定义或挂钩未使用回调。
  • I'm not sure how to make callbacks and promises work here at the same time, it may be possible but you'll have to manage that yourself by possibly inspecting the type of the last parameter and then handling it from there.我不确定如何使回调和承诺同时在这里工作,这可能是可能的,但你必须自己管理它,可能检查最后一个参数的类型,然后从那里处理它。

Update: The beforeStep and afterStep hooks are available in CucumberJS 7.x and later更新: beforeStepafterStep钩子在CucumberJS 7.x 及更高版本中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM