Search code examples
javascriptautomated-testscypressassertion

How can I use Cypress' should('include') to check for either of 2 strings?


I have a test that checks various params are in a page's URL.

Eg:

const expectedPath = "myParam=some%20product%20name";
cy.url().should('include', expectedPath);

However, recently these params have been changed and now no longer have the URL space encoded as part of the url on the link, eg:

<a href="someproduct?myParam=some product name">

For some reason, the browser ether converts this to myParam=some%20product%20name or myParam=some+product+name, so sometimes my tests work and sometimes they don't.

Is there a way to test for either of these scenarios? Eg:

const expectedPathA = "myParam=some%20product%20name";
const expectedPathB = "myParam=some+product+name";
cy.url().should('include', (expectedPathA || expectedPathB));

Solution

  • This page Assertions gives various examples of complex assertions.

    The most straightforward is probably

    cy.url().should('be.oneOf', [baseUrl + expectedPathA, baseUrl + expectedPathB])`
    

    or if you want to apply some extra javascript to the value being asserted:

    cy.url().should('satisfy', (url) => {
      return url.endsWith(expectedPathA) ||    // using string function endsWith()
        url.includes(expectedPathB)          // OR using string function includes()
    })
    

    Obviously you chose the inner functions that suit your needs, I gave a couple for instance's above.