Home > Blockchain >  How I can compare a React Component in different pages using Cypress?
How I can compare a React Component in different pages using Cypress?

Time:01-05

I want to compare if a component is the same in another page using Cypress. Example: I have a Pricing Component in Home, I want to test if the values in Pricing Page is the same.

I tried this, but don't works:

describe('Comparar o componente Pricing em diferentes páginas', () => {

    it('', () => {
        cy.visit('http://localhost:3000')
        cy.get('.package-name').contains('Iniciante').invoke('text').as('name')

        cy.visit('http://localhost:3000/pricing')
        cy.get('.package-name').contains('Iniciante').invoke('text').as('name2')

        expect("@name").to.be.eq("@name2")

    })
    
})

CodePudding user response:

The alias you set are not like variables. Use a .then() to extract it's value.

You can also set http://localhost:3000 as baseUrl in cypress.config.js.

This is how your test would work:

cy.visit('/')
cy.get('.package-name').contains('Iniciante').invoke('text').as('name')

cy.visit('/pricing')
cy.get('.package-name').contains('Iniciante').invoke('text').as('name2')

cy.get('@name').then(name => {
  cy.get('@name2').then(name2 => {
    expect(name).to.be.eq(name2)
  ])
})

CodePudding user response:

To compare if a component is the same in another page using Cypress, you can follow these steps:

Navigate to the page that contains the component you want to compare. For example, if you want to compare the pricing component on the home page, you would navigate to the home page.

Use Cypress commands to retrieve the values of the component from the page. For example, you might use cy.get() to select the element or elements that contain the values you want to compare, and then use .text() or .val() to retrieve the values as a string.

Navigate to the other page that contains the component you want to compare. For example, if you want to compare the pricing component on the home page to the pricing component on the pricing page, you would navigate to the pricing page.

Use Cypress commands to retrieve the values of the component from the second page.

Use Cypress commands to compare the values retrieved from the two pages. For example, you might use cy.wrap() to wrap the values in an object, and then use .should() with the eq() or deepEqual() assertion to compare the values.

Here is an example of how this might look in code:

// Navigate to the home page
cy.visit('/home');

// Retrieve the values of the pricing component from the home page
const homePageValues = cy.get('#pricing-component').text();

// Navigate to the pricing page
cy.visit('/pricing');

// Retrieve the values of the pricing component from the pricing page
const pricingPageValues = cy.get('#pricing-component').text();

// Compare the values from the two pages
cy.wrap(homePageValues).should('deepEqual', pricingPageValues);

  • Related