Pikk
Pikk

Reputation: 2743

how to check url and its parameters? Eq assertion not working

I need to check specific parameters of a URL that is on a button.

This is what I did:

 cy.get('.send-button-url')
      .should('have.attr', 'href')
      .and('eq', 'mailto:[email protected]?subject=&body=')
      .then(url => {
        const arr = url.split('.com?')[1].split('&')

        const paramObj = {}
        arr.forEach(param => {
          const [key, value] = param.split('=')
          paramObj[key] = value
        })

        cy.get('input[placeholder*="Subject"]')
          .invoke('val')
          .then(sometext => cy.log(sometext)) // this one shows `log ` empty. That's good, because the input field is empty at the beginning. 
        cy.wrap(paramObj).then(obj => {
          expect(obj.subject).to.eq(
            cy
              .get('input[placeholder*="Subject"]')
              .invoke('val')
              .then(sometext => sometext),
          )
        })
      })

It gives me:

AssertionError expected '' to equal { Object (specWindow, chainerId, ...) }

The Subject is empty at the beginning at should compare to empty.

If I run

            cy
              .get('input[placeholder*="Subject"]')
              .invoke('val')
              .then(sometext => cy.log(sometext),
          )

it shows log with empty text. And it's good.

What I am doing wrong and how to fix it?

Upvotes: 1

Views: 283

Answers (1)

TesterDick
TesterDick

Reputation: 10535

It might be easier to extract the href subject using URL to parse the href, which is built into the browser.

cy.get('.send-button-url')
  .should('have.attr', 'href')
  .and('eq', 'mailto:[email protected]?subject=&body=')
  .then(href => {

    const url = new URL(href)
    const subject = url.searchParams.get('subject')

    cy.get('input[placeholder*="Subject"]')
      .invoke('val')
      .should('eq', subject)
  })

This works for this HTML with a blank subject

<a class="send-button-url" href="mailto:[email protected]?subject=&body=" ></a>
<input placeholder="Enter the Subject" value="">

To test with a non-blank subject "Cypress"

<a class="send-button-url" href="mailto:[email protected]?subject=Cypress&body=" ></a>
<input placeholder="Enter The Subject" value="Cypress">

you would then need to change the .and() assertion, or parameterize it

const subject = 'Cypress'
const expectedHref = `mailto:[email protected]?subject=${subject}&body=`

cy.get('input').type(subject)

cy.get('.send-button-url')
  .should('have.attr', 'href')
  .and('eq', expectedHref)
  .then(href => {

    const url = new URL(href)
    const subject = url.searchParams.get('subject')

    cy.get('input[placeholder*="Subject"]')
      .invoke('val')
      .should('eq', subject)
  })

Upvotes: 1

Related Questions