Home > database >  Iterating through multiple files in a folder (cypress)
Iterating through multiple files in a folder (cypress)

Time:08-29

I've got multiple json files in a folder which i need to read one by one for testing API. How can i read each file and use it in a different test. Currently I'm reading files using cy.task(), but cy.task() is not available outside it()

describe("Test JSON", () => {
  it(`get file located on test folder`, () => {
    cy.task("getFiles", "cypress/fixtures/jsons/").then((files) => {
      files.forEach((file) => {
      cy.fixture(`jsons/${file}`).then((testJson) => {
            cy.request({
              method: "POST",
              url: Cypress.config().baseUrl,
              body: testJson,
            }).then((response) => {
              expect(response.status).equal(200);
            });
          });
        });
      });
    });
});

(getFiles is a plugin to read filenames in a directory using fs)

How can i run different tests for different files?

CodePudding user response:

Assuming your cypress.config.js with task definition looks like this

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

const getFiles = (path) => {
  return fs.readdirSync(`${__dirname}/${path}`)
}

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        getFiles(path) {
          return getFiles(path)
        }
      })
    },
  },
});

invoke getFiles() inside setupNodeEvents and add the list of files to config.env

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

const getFiles = (path) => {
  return fs.readdirSync(`${__dirname}/${path}`)
}

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      config.env.jsonFiles = getFiles('cypress/fixtures/jsons/')
      return config
    },
  },
});

In the test, read the files from Cypress.env()

const files = Cypress.env('jsonFiles')

files.forEach((file) => {

  it(`tests "${file}"`, () => {
    cy.fixture(`jsons/${file}`).then((testJson) => {
      ...
    })
  })
})

If you want a different set per spec, add multiple locations to Cypress.env()

config.env.jsonFiles1 = getFiles('cypress/fixtures/jsons1/')
config.env.jsonFiles2 = getFiles('cypress/fixtures/jsons2/')

Or you can experiment with fs-readdir-recursive and read everything in /fixtures and folders below.

  • Related