Search code examples
typescriptcucumberjs

How do I use Hooks (before / after) with cucumber-js-tsflow?


I'm currently writing a proof of concept automation solution in Typescript using cucumber-js-tsflow, and I'm trying to replicate the Hooks setup that I have previously implemented in other solutions that used specflow.

Firstly I thought I would add a before and after hook to a separate hooks file at the location features/support/hooks.ts, as it was a proof of concept I just wanted it to log some text to the console:

import { binding, before, after } from 'cucumber-tsflow';

@binding()
export class Hooks {
  @before()
  public static logMessageToConsoleBeforeTestRun(): void {
    console.log('Before test message.');
  }

  @after()
  public static logMessageToConsoleAfterTestRun(): void {
    console.log('After test message.');
  }
}

The above didn't log the expected message to the console when I came to run the scenarios.

I then tried to simplify things, by adding the same code above to the steps file rather than the hooks file and reran, but its still not writing the expected message to the console.

In creating the above code I did follow the documentation in the readme file for cucumber-js-tsflow (https://github.com/timjroberts/cucumber-js-tsflow#readme), but there isnt a huge amount of detail and I'm realy unsure what I could have missed.

Has anyone else had a similar issue and been able to overcome it?


Solution

  • There are 2 changes what you need to do in your hooks file: 1) Do not create hooks file as a class 2) Use below format:

    let { setDefaultTimeout, After, Before, AfterAll, BeforeAll } = require('cucumber');
    
    Before({tags: '@tagName'}, async function() {
    
    console.log('print your info');
    });
    

    This block will be executed when ever you tried to execute a scenario which is tagged with that specified tag name mentioned in above code.