A+ promises

Although it’s documented on https://github.com/cucumber/cucumber-js it wasn’t clear to me what the best is to deal with callbacks in step definitions. After working with cucumber-js for a while it is now clear. So let me share my experiences with you in this area.

When you run it for the first time and have not implemented any of the steps you will get the following snippits:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

this.Given(/^there isadefaultcallback$/,function(callback){

// Write code here that turns the phrase above into concrete actions

callback.pending();

});

this.When(/^the promise has been made$/,function(callback){

// Write code here that turns the phrase above into concrete actions

callback.pending();

});

this.Then(/^something isasserted$/,function(callback){

// Write code here that turns the phrase above into concrete actions

callback.pending();

});

As you can see the default behavior is a callback. So it is easy to implement the Give to set up the stage.

1

2

3

4

this.Given(/^there isadefaultcallback$/,function(callback){

api.addFilter('title','something');

callback();

});

Now usually the When step involves some kind of back-end call and promises are a common way to handle this.
The great thing is that we can you return a promise as-is, but the catch here is to remove the callback from the arguments. There is some magic going on there and if you leave it in you won’t go to the next step and the whole process will keep hanging. I found myself using console.log quite a few times.

JavaScript

1

2

3

this.When(/^the promise has been made$/,function(){

returnapi.myPromise();

});

In the Then step we assert the outcome the promise by getting the state (for example). Also here we don’t need the callback, because if our assertion fails it will throw an error and your scenario failed. Otherwise it can carry on silently like the documentation indicates.

JavaScript

1

2

3

this.Then(/^something isasserted$/,function(){

api.getState().title.should.equal('something');

});

Now to be honest this made the experience of using cucumber-js a lot better. It is a very good tool to have in my daily work and hope this article will help you in that area as well.

One last thing… All of the above can also be achieved with only callbacks, however this makes the step definitions a whole lot messy-er and that’s bad when your projects grows bigger.