testing_library_dom/queries/
alt_text.rs1use regex::Regex;
2use web_sys::HtmlElement;
3
4use crate::{
5 build_queries,
6 error::QueryError,
7 query_helpers::query_all_by_attribute,
8 types::{Matcher, MatcherOptions},
9};
10
11pub fn _query_all_by_alt_text<M: Into<Matcher>>(
12 container: &HtmlElement,
13 alt: M,
14 options: MatcherOptions,
15) -> Result<Vec<HtmlElement>, QueryError> {
16 let valid_tag_regex = Regex::new(r"^(img|input|area|.+-.+)$").expect("Regex should be valid.");
17
18 Ok(
19 query_all_by_attribute("alt".to_string(), container, alt, options)?
20 .into_iter()
21 .filter(|node| valid_tag_regex.is_match(&node.tag_name()))
22 .collect(),
23 )
24}
25
26fn get_multiple_error(
27 _container: &HtmlElement,
28 alt: Matcher,
29 _options: MatcherOptions,
30) -> Result<String, QueryError> {
31 Ok(format!("Found multiple elements with the alt text: {alt}"))
32}
33
34fn get_missing_error(
35 _container: &HtmlElement,
36 alt: Matcher,
37 _options: MatcherOptions,
38) -> Result<String, QueryError> {
39 Ok(format!(
40 "Unable to find an element with the alt text: {alt}"
41 ))
42}
43
44build_queries!(
45 _query_all_by_alt_text,
46 get_multiple_error,
47 get_missing_error,
48 alt_text,
49 crate::types::Matcher,
50 crate::types::MatcherOptions
51);
52
53pub use internal::{
54 find_all_by_alt_text, find_by_alt_text, get_all_by_alt_text, get_by_alt_text,
55 query_all_by_alt_text, query_by_alt_text,
56};