Handle testing one text or another text in Cypress test (language variations)

Viewed 42

The application I'm testing has multi-language capability, so I need to be able to test for text that can be one thing or another and either should pass the test.

Although it's a conditional test, I don't want to use if() statements which would mean I then lose retry capability of cypress commands (i.e flaky tests).

For example, how can I check a string that can be one of several languages without repeating the test?

cy.get('div')
  .should('contain', 'Hello')
  .or('contain', 'Hola')
3 Answers

One way to conditionally check for one string or another is to create a dictionary of alternate words, for example

const dictionary = {
  greeting: ['hello', 'hola', 'namaste'],
  ...
}

Then apply it in the test as a regular expression with the use of a helper function

const language = (selector) => {
  const options = dictionary[greeting];
  return new RegExp(options.join('|'), 'i')  // make it case-insensitive with 'i'  
}

cy.get('div')
  .should('contain', language('greeting'))  // regex is  /hello|hola|namaste/i

It's also possible to use the oneOf assertion, but you lose case-insensitive since comparison is strict.

cy.get('div')
  .should('contain.oneOf', dictionary['greeting'])

You can create an array with the possible texts and then apply a to.be.oneOf assertion.

const greetingsArray = ['hello', 'hola', 'hallo']
cy.get('div')
  .invoke('text')
  .then((text) => {
    expect(text.toLowerCase()).to.be.oneOf(greetingsArray)
  })

You can use jQuery to check contains on or other value.

Use .should() get retry if text is asynchronous.

cy.get('div')
  .invoke('text')
  .should((text) => {
    const found = greetings.some(greeting => text.includes(greeting))
    expect(found).to.eq(true)
  })
Related