Enhance the step implementation in Cucumber-js

Background

In my TypeScript project, I am utilizing https://github.com/cucumber/cucumber-js. The code snippet below showcases a typical cucumber implementation:

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

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

Objective

My goal is to find a way to enhance the functionality of the Given function. Specifically, I want to:

  • Execute a pre-defined action before the code inside Given runs. For instance, I would like to print out the first argument in the Given statement (e.g., Page is up and running).
  • Avoid making changes to the existing step implementations.

Within the index.d.ts file, each step has two alias function definitions, as shown below:

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

Answer №1

In the initial release of CucumberJS, there were a variety of hooks at your disposal, including beforeStep. However, in newer versions like 6.0.5, you can still achieve similar functionality by utilizing setDefinitionFunctionWrapper. For example:

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

Check out this online demonstration:

Important notes and considerations:

  • This method will wrap both step definitions and hooks.
  • This specific implementation assumes that neither the step definition nor hook is using a callback.
  • Tackling callbacks and promises simultaneously may be tricky; it could potentially require individual management based on parameter inspection and type handling.

Update: The latest versions of CucumberJS, starting from version 7.x, reintroduced the beforeStep and afterStep hooks. More details can be found here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on transforming a Firebase Snapshot child into a personalized object in a React Native environment

I'm looking for a way to retrieve data from Firebase Realtime Database and display it in FlatList format. What is the most efficient method for extracting the child value and converting it into a custom object? For example: class CustomObject { ...

Incorporating dynamic form elements using Vue.js within a targeted div

Here is the HTML and Vue.js code that I have: <table class="table"> <thead> <tr> <td><strong>Title</strong></td> <td><strong>Description< ...

End of ImageButton tag

I am currently working on this code : <div runat="server" class="slide"> <img src="images/picto_detail.gif" onclick='<%# Eval("CampagneRappelId","hideshow(\"details{0}\")")%>' /> <div id='details<%# Eval("C ...

What could be the reason behind my Heroku app suddenly crashing without any visible errors?

After successfully starting the Nest application, about 50 seconds later it transitions from 'starting' to 'crashed'. The last log entry before the crash is a console log indicating the port number. View Heroku logs after successful bui ...

Save unique data for each tab in the browser

In my web application, I store information about recently visited pages, which I'll refer to as type A. When a user visits a different page type, called B, I display a menu at the top with a button that links back to the most recently visited A-page. ...

Finding elements based on their position using Javascript

I'm searching for an optimal method to identify all elements located within a specific range of pixels from the top of the page. Currently, I have implemented a straightforward test called inRange function inRange(el, from, to) { var top = el.offs ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Unlock the secrets of creating a pop-up with qtip

I am working on qtip code that generates a popup when a specific link is clicked. I'm wondering if there's a way to use jQuery to determine if the link with the id "test2" has been clicked or not. Thank you, James <ul> <li><a id= ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

What is the best way to retrieve user data and format the output using JavaScript into a structured form?

I am trying to achieve the functionality shown in this image: My goal is to extract user input from a form and display it on my webpage using JavaScript. Below is the code snippet that I have been working on. Code: function show(){ var ...

Can you explain the significance of "===" and the key distinctions it has from "=="?

Related Query: Javascript === vs == : Does it matter which “equal” operator I use? What is the significance of using === in jQuery/Javascript, and how does it differ from ==? For instance, in my code snippet below: if ($this.val() != &a ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Explaining the process of defining `this.props` and storing data in the global Redux state

I am currently diving into the world of react and Redux and I'm using a react project on GitHub called overcode/rovercode-ui as a learning tool for understanding react and Redux. As I explore this project, I have come across some intriguing questions. ...

iOS device encounters failure with Ajax CORS request and redirect

I am experiencing an issue where a URL is being redirected to another domain by the server. My test code is very simple: $.ajax({ type:"GET", url:"{MYURL}", success:function(d){alert('response');} }) You can che ...

What is the best way to implement a CSS transition for styles that are dynamically created by React?

I have a situation where I am using a button component that is styled based on a theme provided by a context: The code in Button.js looks like: () => { const theme = useContext(themeContext); // { primaryColor: "blue" } return <button className ...

Create a boolean flag in Java using JavaScript

Hey there, I'm working on a project where I need to detect the user's browser in JavaScript. For Safari browsers, I have to download an audio file, while for every other browser I need to play the audio. Currently, my code can correctly identify ...

The $.get method in AJAX/jQuery is functioning properly, however, there seems to be an issue with

Yesterday, I successfully made my first AJAX call by using this function that was connected to a button click event. function ajaxFunction(){ $.get("ajax/calendar.php", function(data){ $('#ajaxResponse').html(data); }); }; Now, I want t ...

Having issues with the functionality of single click in jQuery

I tried to remove the attribute element from a list item, but I am struggling to achieve the desired outcome. When clicking on a list item, it should add a class called "important," otherwise, the class should not exist. Here is my attempt using jQuery: ...

Encountering an issue where the useMutation function is not recognized on the DecorateProcedure<MutationProcedure> type while attempting to utilize the useMutation feature

Currently, I am utilizing the NextJS app router. I am attempting to invoke a rather straightforward route: import { z } from "zod"; import { createTRPCRouter, publicProcedure } from "~/server/api/trpc"; // document sending user email to waitlist da ...

Would it be possible to use a script to convert the y-axis values of the chart into Arabic numerals?

Currently, I am working on creating line and pie charts, but I need the Y-axis to display Arabic language. $('button').on('click', function(e) { $('#pie-chart3').empty(); var type = $(this).d ...