I'd like to generate identical tests with variable data in Cypress. The idea is that testers can create new folders in the fixtures folder, and these folders will automatically be picked up and used to generate new tests.
I've created this snippet in my plugins/index.js. When cy.task('getAllDirectories', 'someURL') is called it will give me a list of all sub-directories inside someURL.
const { readdirSync, lstatSync } = require('fs');
const { join } = require('path');
const _ = require('lodash');
const isDirectory = source => lstatSync(source).isDirectory();
module.exports = (on, config) => {
on('task', {
getAllDirectories(source) {
const fullSource = `${process.cwd()}/cypress/${source}`;
return readdirSync(fullSource)
.map(name => join(fullSource, name))
.filter(isDirectory)
.map(name => _.last(name.split('/')));
},
});
};
This seems to work just fine, I've managed to call it successfully inside it() and before() in Cypress. The problem however is that since these dynamically generated tests are the only ones in this file, this code inside my context doesn't run at all.
let TESTS = [];
before(() => {
cy.task('getAllDirectories', '').then((output) => {
TESTS = output;
cy.log(TESTS);
});
});
Even when I add a dummy test like it('dummy', () => {}), the TESTS variable is set to the new name array, but it's too late to generate tests, when I try to iterate it below the before method.
TESTS.forEach((TEST) => {
it(`Validates request: ${TEST}`, () => {
...
So I figured I need to call cy.task outside of a test or before hook, however putting it only inside context() says that cy.task must be ran inside a test.