Jake
Jake

Reputation: 1370

Cypress expect string to contain one element or another element

I'm working on some Cypress assertions that is looking at a value to contain a string. Right now it's a success if the data shows "AM" but I'd also like for it to be correct if it shows "PM".

cy.get('.v-list__tile__content')
  .then(($info) => {
    expect($info, 'Delivery Information').to.have.length(3)
    expect($info.eq(0), 'Address').to.contain('Chicago')
    expect($info.eq(1), 'Time').to.contain('AM')
    expect($info.eq(2), 'Year').to.contain('2019')
 })

The data is actually showing Address, full time, and then year. Is there an assertion that allows for checking contains against two/multiple strings? Maybe a version of oneOf but with contains? I'm struggling to find documentation that allows for something like that. I think doing a conditional would defeat the purpose since I want to assert it's either AM/PM. Typically the data will come back like 12:00 PM so unfortunately I can't hit on the number and do an assertion there.

My JS is mediocre but maybe doing

arr = ["AM", "PM"];
var el = document.getElementByClassName('.v-list-tile__content')[1];
var txt = el.includes(arr);

So how do I do an assertion in Cypress on contains for multiple strings?

Upvotes: 0

Views: 3480

Answers (1)

Porter Lyman
Porter Lyman

Reputation: 355

You could try using something along these lines in a for loop.

let arr;
let element;
arr = ["AM", "PM", "Dog", "Cat", "Bug", "Whatever"]
element = '.v-list-tile__content'

   function checkAgainstArr(arr, element) {

     let i;
     for (i = 0; i < arr.length; i++) { 
       if (cy.get(element).contains(arr[i])) {
         return true;
       } else {
         if (i === arr.length) {
           return false; 
         }
       }
     }
   }

expect(checkAgainstArr).to.be.true;

Basically, it checks how long the array is (here, it's 6), and then tries that many times to compare the element's text against each item in the array. If it finds it, it returns true. Then, you can call that function (with two parameters, array and element) and check for truthy/falsy.

Upvotes: 1

Related Questions