Is there a way to do assertions for texts in spec level in Cypress?

Viewed 86

Cypress is really a cool tool and the below thing is stopping me from migrating scripts from protractor to cypress..

this.getBreadcrumText = async (value) => {
  const a = await cy.xpath("//*[contains(@data-testid,'breadcrumbs-route-Dashboards')]")
    .text().then(txt => {
      expect(txt).equal('Dashboards')
     });       
  cy.log('------', a)
}`

In the above method I was able to expect the text within the page. If I want to do assertions in the spec level I should be able to return the value of a to the spec file where this function is called, which is currently not happening. Ideally in the test/spec file we should not be using the element references also.

Basically in spec file if I use

expect( dashboardPage.getBreadcrumText()).equal('Dashboards')

it is not working. Any way to achieve this?

2 Answers

Cypress is queue-based which means you have to return things via a .then() callback, similar to promises.

So

Page object

this.getBreadcrumText = () => { 
  // returns a command chainer from which you can access text via .then()
  return cy.xpath("//*[contains(@data-testid,'breadcrumbs-route-Dashboards')]")
    .text();
}

Test

dashboardPage.getBreadcrumText()
  .then(text => {
    expect(text).equal('Dashboards')
  })

or, fire the assertion inside the page object using value passed in

Page object

this.getBreadcrumText = (value) => { 
  cy.xpath("//*[contains(@data-testid,'breadcrumbs-route-Dashboards')]")
    .invoke('text')
    .should('eq', value);
}

Test

dashboardPage.getBreadcrumText('Dashboards');

I'm not sure all the selectors here are kosher, if any problems try those given by @RosenMihaylov

The first important part is - async/await can not be used directly in cypress.

For asserting text I use this plugin and here I present you a simple tmplate for text assertions:

cy.xpath("//*[contains(@data-testid,'breadcrumbs-route-Dashboards')]")
    .text()
    .should('eq', 'Dashboards')

Also you can use JQ .text where you need to use should instead of then, because it retryes for a few seconds for the expected result:

cy.xpath("//*[contains(@data-testid,'breadcrumbs-route-Dashboards')]")
   .should(element =>{  
       expect(Cypress.$(element).text()).to.equal('Dashboards')
   })
Related