Using Cypress functions in different files

I am trying to use cypress functions in files different from the main one (which is the test file). I am wondering if it is possible. Actually, I did this: this is the code in my test.js file; note that the first function is what I'm trying to do; the second function works normally and I have no problem with that. The reason why I am trying to do that is that I could need to reuse the same function multiple times.

my tree folders:

static_copied
    pages
        cities
            Rome
            New York
            Bombay
            Tokyo
            London
            Moscow

test.js file:

const pathCities = 'static_copied/pages/cities'

it('Retrieve cities from static and divide links', () => {
      

      let cities1 = misc.retrieveCities()
      console.log(cities1)

      // this works
      cy.task('readFolder', pathCities).then(cities => {
        console.log('cities ', cities, typeof cities)    // prints an array of cities, and 'object'
      })
    })
  })

my misc.help.js file:

const pathCities = 'static_copied/pages/cities'

module.exports = {
    retrieveCities,
    [...]
}

[...]

function retrieveCities() {
  cy.task('readFolder', pathCities).then(res => {
    console.log('here', res, typeof res)
    return res
  })
}

and finally my cypress/plugins/index.js file:

const fs = require('fs')

// opens devTools by default
module.exports = (on, config) => {
  [...]

  // reads a folder, both folder and file names
  on('task', {
    readFolder(path) {
      let foldersAnFiles = fs.readdirSync(path, 'utf8')
      console.log('--->', foldersAnFiles, typeof foldersAnFiles)

      let folders = []

      // if its a file, exclude from result
      foldersAnFiles.filter(function (folder) {
        if (folder.indexOf('.') === -1) {
          folders.push(folder)
        }
      })
      
      return folders
    },
  })
}

What happens is that in misc.help.js file, print is correct: in retrieveCities() function, this console log console.log('here', res, typeof res) correctly prints an array. But when i return it in the main test file, console.log(cities1) prints undefined.

Is there a way to pass to the main file my result?



Read more here: https://stackoverflow.com/questions/67018282/using-cypress-functions-in-different-files

Content Attribution

This content was originally published by Don Diego at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: