How to share data between steps in Cucumber with WendriverIO?
Sometimes we need to share data between different steps in WebdriverIO when we are building tests with Gherkin, to not send the same request several times within the same test.
Of course, our tests should be atomic. It is not recommended to share information between different tests or scenarios. In this example, it is a single test.
Feature file
We have the feature file worldtimeapi.feature where we specify a timezone and we want to get the current time of that timezone:
Feature: Timezones in Worldtime API
Scenario Outline: API handles properly the time in existing timezones
Given I have a list of timezones
When I select the timezone in <timezone_position>th position
Then I should get the time for the selected timezone
Examples:
| timezone_position |
| 45 |
Setting the value
In step 2 When I select the timezone in <timezone_position>th position we send the position of the timezone (in an array with all the timezones) and we save selectedTimezone with the function setValue setValue(“selectedTimezone”, selectedTimezone);
When(/^I select the timezone in (.*)th position$/, async (position) => {
const selectedTimezone = await worldTimePage.getTimezoneByIndex(position);
await setValue("selectedTimezone", selectedTimezone);
});
Getting the value
In step 3 we use the selectTimezone previously set in step 2 to get the current time of that timezone with the function getValue getValue(“selectedTimezone”);
Then(/^I should get the time for the selected timezone$/, async () => {
const selectedTimezone = await getValue("selectedTimezone");
const currentHourInTimezone = await worldTimePage.getCurrentHourInTimezone(
selectedTimezone
);
await expect(currentHourInTimezone).toMatch(
/^(?:\\d{4})-(?:\\d{2})-(?:\\d{2})T(?:\\d{2}):(?:\\d{2}):(?:\\d{2}(?:\\.\\d*)?)(?:(?:-(?:\\d{2}):(?:\\d{2})|Z)?)$/
);
});
To use the functions setValue and getValue, install the package @wdio/shared-store-service and add setValue and getValue to config file wdio.conf.js
import { setValue, getValue } from "@wdio/shared-store-service";
In onPrepare (also in wdio.conf.js) we add (initialize) the vars we are going to share between steps (names and types) with the function setValue
onPrepare: [
async function (config, capabilities) {
await setValue("selectedTimezone", []);
await setValue("timezoneExists", []);
},
],
In services (also in wdio.conf.js) we add shared-store
services: ["chromedriver", "shared-store"],
And, that’s all, we are ready to run our tests.
See the code in github