logiccypresscypress-custom-commands

How can I get my cypress custom command to ingest this data (i think i structured the data wrong)?


Alright, as the title says- i'm trying to write a custom command for a cypress test suite. The situation as as follows: I have several tests that need to select an indeterminate number of fields and select an option from the each fields list of drop downs.

The logic for this is crayons-in-mouth simple and works fine:

cy.get(selector)
  .select(selection)
  .scrollIntoView()

and this works great. But because I use it a lot it's a lot of highly repetitive code so I'm trying to create a custom command where I can just inject an array of arrays (various sets of selectors and selections depending on the situation) into it and it'll do the rest.

This is the custom command as I have it written now.

commands.js

Cypress.Commands.add("assignImportFields", (array) => {
  cy.wrap(array).each((selector, selection) => {
    cy.get(selector)
      .select(selection)
      .scrollIntoView()
    cy.log('using ' + selector + ' to select ' + selection)
  })
})

I have the data in a seperate file that looks like this:

data.js

const importFields = {
  actorListImports : [
    [selectors.lastName, 'Last_Name'],
    [selectors.firstName, 'First_Name'],
    [selectors.phoneNum, 'Phone_Number']
  ]
}

exports.importFields = importFields;

and finally, in my test file:

tests.js

const {actorListImports} = data.importFields;
cy.assignImportFields(actorListImports)

The response I get from this is that the 'select' failed because it requires a dom element. My selectors are fine, so I think it's trying to use an entire array (both selector and selection at once) as the selector instead of the first part of the array.

I know i'm not structuring the data correctly, but i've tried a few different variations of it and my primitive monkey brain just can't put together.

Can someone help me identify what's wrong with how i've structure this?


Solution

  • You need to de-structure the array elements in the .each() parameter list, like this cy.wrap(data).each(([selector, selection])

    This is a minimal example:

    const selectors = {
      'lastName': 'lastName'
    }
    
    const data = [
      [selectors.lastName, 'Last_Name'],
      // [selectors.firstName, 'First_Name'],
      // [selectors.phoneNum, 'Phone_Number']
    ]
    
    cy.wrap(data).each(([selector, selection]) => {
      console.log(selector, selection)
      expect(selector).to.eq('lastName')                // passing
      expect(selection).to.eq('Last_Name')              // passing
    })