vite findByText
Code

Vite findByText to get all the elements

Vite findByText method could help us a lot, especially while testing any kind of i18n and similar. Of course we should always get the proepr component / element but such methods are very usefull when developing and debugging, later we can scrape it all. Later, when we know it works as we expect it.

FindByText method can be especially usefull when we have a big flat table that may or may not be dynamically populated. Works great as a function to watch the vaues beeing present in the dom so we can catch the proper moment. Altough we could use the debugger, i find that printing a lot of stuff helps to make more thing visible at once 🙂

FindByText – example code

function findByText(domComponentWrapper, textToFind, selector = '*') {
  // Find all elements matching the provided selector
  const elements= domComponentWrapper.findAll(selector);

  // Iterate through each found element
  for (let i = 0; i < elements.length; i++) {
    const element= elements[i];

    // Check if the text content of the current element, after trimming whitespace,
    // matches the provided string after trimming whitespace
    if (element.text().trim() === textToFind.trim()) {
      // If the text content matches the provided string, return the element
      return element;
    }
  }

  // If no matching element is found, return an error
  return createWrapperError('No elements has been found with text=', textToFind);
}

Piotr Kowalski