Last active
June 25, 2018 11:15
-
-
Save paulwib/3e41ee490bde4b66c5a17afcb0362cdf to your computer and use it in GitHub Desktop.
Functional Cucumber.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { defineStep } = require('cucumber'); | |
const arity = require('util-arity'); | |
/** | |
* Wrap a step function so it is passed the `world` scope as the first argument. | |
* Allows writing step definitions in a "purer" more functional style without | |
* worry about what `this` is, which is especially annoying when calling functions | |
* from other functions. | |
* | |
* Internal helpers expect world as the first argument, which is fine when they're | |
* calling each other, this is just to wrap the initial step definition function. | |
* | |
* Internally you can also choose to just pass bits of the world, for example driver | |
* helpers can just be passed the driver. | |
* | |
* Need to return a function with corrected arity as cucumber checks | |
* the arity matches it's expectations. The arity is shortened by one to | |
* ignore the first argument i.e. the reference to `this`. | |
* @see https://github.com/cucumber/cucumber-js/issues/514 | |
* | |
* @param {Function} fn - the function to wrap | |
* @return {Function} | |
*/ | |
function withWorld (fn) { | |
return arity(fn.length - 1, function () { return fn(this, ...arguments); }); | |
} | |
/** | |
* Helper to go to URL. | |
* | |
* @param {IWebDriver} driver | |
* @param {String} url | |
* @return {Promise} | |
*/ | |
function gotoUrl (driver, url) { | |
return driver.get(url); | |
} | |
/** | |
* Helper to go to Google home page. | |
* | |
* @param {Object} world | |
* @return {Promise} | |
*/ | |
function gotoGoogle (world) { | |
return gotoUrl(world.driver, 'https://google.com'); | |
} | |
// Define cucumber step - `withWorld` is only used on the initial method, internally it is passed. | |
defineStep('I visit Google', withWorld(gotoGoogle)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment