Using Cucumber Hooks in Angular

sebrittainclark profile image Sarah Brittain Clark ・2 min read

I've been using Cucumber and Protractor to write e2e tests for my Angular applications for a few months now. I recently learned about Cucumber's event hooks from someone using Cucumber for their Java integration testing, and I thought they'd help me clean up my tests and add some new functionality beyond what I was already doing with the Background step. I didn't have much luck finding documentation on using Cucumber with Javascript or Typescript, so I tried following the Java documentation until I found something that worked. Hours later I noticed that at the top of the Cucumber documentation there was an option to display the documentation for Java, Ruby, Kotlin, or Javascript, but given how difficult it was to find that Javascript documentation, I wanted to document it for myself.

I created a file called hooks.ts, but this code could be added to any of your e2e files. Then I just had to pull in the Before and After hooks.

const { Before, After } = require('cucumber');

Before( function(scenario) {
    //do something before every scenario

After( function(scenario) {
    //do something after every scenario

You don't need any additional imports or code, everything will work as soon as these hooks are added to your project. From there it's very easy to set up hooks for specific tags.

const { Before, After } = require('cucumber');

Before( '@example', function(scenario){
    //do something before every @example scenario

After( '@example', function(scenario){
    //do something after every @example scenario

This allow for better control over the state of your application, and more consistent e2e testing. Cucumber has even more examples of what you can do with hooks to improve your e2e testing.

Posted on by:

sebrittainclark profile

Sarah Brittain Clark


I'm a full-stack software engineer working primarily in Angular & Java.


markdown guide