menu

Testing Library

Simple and complete DOM testing utilities that encourage good testing practices.

Channels
Chat
view-forward
# All channels
view-forward
# General
view-forward
# General Help
view-forward
# Angular Help
view-forward
# Cypress Help
view-forward
# DOM Help
view-forward
# React Help
view-forward
# Svelte Help
view-forward
# TestCafe Help
view-forward
# Vue Help
view-forward
Team

Proper use of getAllByText to find the target matching element

January 20, 2020 at 8:35pm

Proper use of getAllByText to find the target matching element

January 20, 2020 at 8:35pm (Edited 2 months ago)
I have a document with two buttons. One is 'save' and the other is 'save as'. In the test to make sure the 'save' button appears on the page, I use 'getAllByText' to find elements that match /save/i. What is the best way to make sure I am looking at the 'save' button instead of the 'save as' button?
Index in the array: I know that the 'save' button comes before the 'save as' button. So I could just look at getAllByText(/save/i)[0]. But that seems like bad practice, because it will return the wrong element if I decide to rearrange the buttons.
Array.find: I could use Array.find to find e.g. an element with textContent.length === 4. This feels a little redundant, like if I'm doing that I should just pass a custom matcher function to the query in the first place. But it will work and doesn't rely on the component order.
Are either of these best practice, or is there another method?

January 20, 2020 at 10:18pm
I used to do this by regexp. As you can pass a regexp to get by text, you can do getByText(/^save$/i) or getByText(/^save as$/i) depending on which one you want.
like-fill
1
  • reply
  • like