In this scenario, we cannot hard-code a single email to test because it may lead to a 409 Conflict error because an account with that email already exists. Therefore, we need to generate a random email each time the test is run. We need to define a new step definition where the data is randomly generated each time:
When(/^user types in an? (in)?valid (\w+) in the (?:"|')([\.#\w-]+)(?:"|') element$/, async function (invalid, type, selector) {
const textToInput = generateSampleData(type, !invalid);
this.element = await this.driver.findElement(By.css(selector));
return this.element.sendKeys(textToInput);
});
Here, we create a generic step definition and use the yet-to-be-defined generateSampleData function to provide the random data. We will define the generateSampleData function in a new file at spec/cucumber/steps/utils/index.js and, just as we did for in our backend tests, use the chance package to generate the random data.
First, install the chance package:
$ yarn add chance --dev
And then define generateSampleData as follows:
import Chance from 'chance';
const chance = new Chance();
function generateSampleData (type, valid = true) {
switch (type) {
case 'email':
return valid ? chance.email() : chance.string()
break;
case 'password':
return valid ? chance.string({ length: 13 }) : chance.string({ length: 5 });
break;
default:
throw new Error('Unsupported data type')
break;
}
}
export {
generateSampleData,
}