DEV Community

Sarah Brittain Clark
Sarah Brittain Clark

Posted on

3 1

Using Cucumber Hooks in Angular

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
});
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay