0

I want to integrate a function in a spec.ts file where it will read multiple xml data one by one from a directory and will repeat the tests as long as the directories length.

Is there any way to read multiple files or files name from a folder in Cypress or in JavaScript ?

Fody
  • 23,754
  • 3
  • 20
  • 37
Srinjay
  • 11
  • 2

2 Answers2

1

You will need to read the file list in cypress.config.js (for Cypress version 10 and above).

const { defineConfig } = require('cypress')
const fs = require("fs");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {

      const xmlFolder = `${__dirname}/xml-files/`;
      const files = fs.readdirSync(xmlFolder)
        .map(file => `${xmlFolder}/${file}`)     // add folder path

      config.xmlFiles = files                    // put in config for test
      return config
    }
  }
})

In the test,

describe('Creating one test for each XML file', () => {

  Cypress.config('xmlFiles')
    .forEach(fileName => {

      it(`Testing ${fileName}`, () => {

        cy.readFile(fileName)
          .then(xml => {
            ...
          })
      });
    });
})

For Cypress version 9 and below use plugins.index.js:

module.exports = (on, config) => {
  on('before:run', (spec) => {

    const xmlFolder = `${__dirname}/xml-files/`;
    const files = fs.readdirSync(xmlFolder)
      .map(file => `${xmlFolder}/${file}`)     // add folder path

    config.xmlFiles = files                    // put in config for test
  })
  return config 
}
TesterDick
  • 3,830
  • 5
  • 18
  • I am using cypress version 7.7.0 so there s no cypress.config.js file instead I have cypress.json . Could you please help how to proceed in cypress.json – Srinjay Sep 23 '22 at 05:02
  • The newer `cypress.config.js` is a combination of the old `cypress.json` and `plugins/index.js`. This code would go into `plugins/index.js`, I'll add the code for that. – TesterDick Sep 23 '22 at 20:01
0

You can use fs to read the content of a directory, and then we can use Cypress Lodash to iterate through that returned array.

import fs from 'fs';

const files = fs.readdirSync('/my/dir/');

describe('My Tests', () => {
  Cypress._.times(files.length, (index) => {
    it(`does some test for the file: ${files[index]}, () => {
      cy.readFile(files[index]).should(...);
    });
  });
});

agoff
  • 5,818
  • 1
  • 7
  • 20
  • The following error originated from your test code, not from Cypress. > fs is not defined When Cypress detects uncaught errors originating from your test code it will automatically fail the current test. Cypress could not associate this error to any specific test. This error originated from the test case – Srinjay Sep 23 '22 at 04:49