Home > Enterprise >  Cypress extract segment of string with regex for later comparison
Cypress extract segment of string with regex for later comparison

Time:08-05

I'm building a test in cypress where I need to extract part of a label in a button (I already have a selector for it), store it and use it later in the test for a .should('contain', label) assertion.

I've tried doing the following:


cy.assertObjectIsFocused(selector[Cypress.env(common.APP_NAME)].newPlayer.btnNextEpisode);
        cy.get(selector[Cypress.env(common.APP_NAME)].newPlayer.btnNextEpisodeLabel)
          .invoke('attr', common.TEXTURE_TEXT)
          .and('match', /S\d  E\d /)
          .as('nextEpisodeLabel');

        ...

        cy.get('@nextEpisodeLabel').then((label) => {
          cy.get(
            selector[Cypress.env(common.APP_NAME)].newPlayer.playerAssetEpisodeAndSeasonNumbers,
          )
            .invoke('attr', common.TEXTURE_TEXT)
            .should('contain', label);
        });

But it isn't extracting the regex, it's comparing the whole label (I expected the .and('match', /S\d E\d /).as('nextEpisodeLabel'); would store as an alias only the regex of the string, but no, it stores the whole string.

How can I extract only the necessary part of the string so I can later use it in the assertion?

CodePudding user response:

You can do something like this:

cy.assertObjectIsFocused(
  selector[Cypress.env(common.APP_NAME)].newPlayer.btnNextEpisode
)
cy.get(selector[Cypress.env(common.APP_NAME)].newPlayer.btnNextEpisodeLabel)
  .invoke('attr', common.TEXTURE_TEXT)
  .as('nextEpisodeLabel')

...

cy.get('@nextEpisodeLabel').then((label) => {
  cy.wrap(label).should('match', /S\d  E\d /)
  cy.get(
    selector[Cypress.env(common.APP_NAME)].newPlayer
      .playerAssetEpisodeAndSeasonNumbers
  )
    .invoke('attr', common.TEXTURE_TEXT)
    .should('contain', label)
})

Or, if you want to add the alias based on whether the extracted label matches the regex or not, You can do like this:

cy.assertObjectIsFocused(
  selector[Cypress.env(common.APP_NAME)].newPlayer.btnNextEpisode
)
cy.get(selector[Cypress.env(common.APP_NAME)].newPlayer.btnNextEpisodeLabel)
  .invoke('attr', common.TEXTURE_TEXT)
  .then(($nextEpisodeLabel) => {
    if ($nextEpisodeLabel.match(/S\d  E\d /)) {
      cy.wrap($nextEpisodeLabel).as('nextEpisodeLabel')
    }
  })

...

cy.get('@nextEpisodeLabel').then((label) => {
  cy.get(
    selector[Cypress.env(common.APP_NAME)].newPlayer
      .playerAssetEpisodeAndSeasonNumbers
  )
    .invoke('attr', common.TEXTURE_TEXT)
    .should('contain', label)
})
  • Related