Home > Back-end >  Cypress - JS - Array mapping
Cypress - JS - Array mapping

Time:08-03

The code below does what I need to do but I also want to improve the readability actually. Because currently, "%s" gets the whole "data-cy" part as you can see it from the screenshot below.

Instead of displaying "verifies the main product groups ([data-cy="main-group-tab.shoes"]) and filters", how can I display "verifies the main product groups shoes and filters"?

I tried using the .split() method but it didn't work. Should I create another array like; productNames = ['shoes', 'apparel', 'accessories'] and map it?

How would you do that?

Thanks in advance!

const productTabs = ['[data-cy="main-group-tab.shoes"]', '[data-cy="main-group-tab.apparel"]', '[data-cy="main-group-tab.accessories"]']
it.each(productTabs)(`verifies the main product groups (%s) and filters`, (productTabs) => {

  cy.get(productTabs)
    .click();

  availabilityPage.productGroups()
                  .should('be.visible');

  availabilityPage.searchBar()
                  .should('be.visible');
});

The result

CodePudding user response:

Run the tests from products list, and build the selector from it (since they have the same form)

const products = ['shoes', 'apparel', 'accessories']
it.each(products)(`verifies the main product groups (%s) and filters`, (product) => {

  const productTab = `[data-cy="main-group-tab.${product}"]`
  cy.get(productTab)
    .click();

  availabilityPage.productGroups()
                  .should('be.visible');

  availabilityPage.searchBar()
                  .should('be.visible');
});

CodePudding user response:

You can do something like this. Your approach was right. Just use the index number from the current each and then using that access the elements of productNames array, something like this:

const productTabs = [
  '[data-cy="main-group-tab.shoes"]',
  '[data-cy="main-group-tab.apparel"]',
  '[data-cy="main-group-tab.accessories"]',
]
const productNames = ['shoes', 'apparel', 'accessories']
it.each(productTabs, index)(
  `verifies the main product groups ${productNames[index]} and filters`,
  (productTabs) => {
    cy.get(productTabs).click()
    availabilityPage.productGroups().should('be.visible')
    availabilityPage.searchBar().should('be.visible')
  }
)
  • Related